home *** CD-ROM | disk | FTP | other *** search
/ Ian & Stuart's Australian Mac: Not for Sale / Another.not.for.sale (Australia).iso / Dr. Doyle / perl.man < prev    next >
Text File  |  1994-11-11  |  270KB  |  7,195 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLL((((1111))))     UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 4444....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.           perl - Practical Extraction and Report Language
  10.  
  11.      SSSSYYYYNNNNOOOOPPPPSSSSIIIISSSS
  12.           ppppeeeerrrrllll [options] filename args
  13.  
  14.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  15.           Perl is an interpreted language optimized for scanning
  16.           arbitrary text files, extracting information from those text
  17.           files, and printing reports based on that information.  It's
  18.           also a good language for many system management tasks.  The
  19.           language is intended to be practical (easy to use,
  20.           efficient, complete) rather than beautiful (tiny, elegant,
  21.           minimal).  It combines (in the author's opinion, anyway)
  22.           some of the best features of C, sed, awk, and sh, so people
  23.           familiar with those languages should have little difficulty
  24.           with it.  (Language historians will also note some vestiges
  25.           of csh, Pascal, and even BASIC-PLUS.)  Expression syntax
  26.           corresponds quite closely to C expression syntax.  Unlike
  27.           most Unix utilities, perl does not arbitrarily limit the
  28.           size of your data--if you've got the memory, perl can slurp
  29.           in your whole file as a single string.  Recursion is of
  30.           unlimited depth.  And the hash tables used by associative
  31.           arrays grow as necessary to prevent degraded performance.
  32.           Perl uses sophisticated pattern matching techniques to scan
  33.           large amounts of data very quickly.  Although optimized for
  34.           scanning text, perl can also deal with binary data, and can
  35.           make dbm files look like associative arrays (where dbm is
  36.           available).  Setuid perl scripts are safer than C programs
  37.           through a dataflow tracing mechanism which prevents many
  38.           stupid security holes.  If you have a problem that would
  39.           ordinarily use sed or awk or sh, but it exceeds their
  40.           capabilities or must run a little faster, and you don't want
  41.           to write the silly thing in C, then perl may be for you.
  42.           There are also translators to turn your sed and awk scripts
  43.           into perl scripts.  OK, enough hype.
  44.  
  45.           Upon startup, perl looks for your script in one of the
  46.           following places:
  47.  
  48.           1.  Specified line by line via ----eeee switches on the command
  49.               line.
  50.  
  51.           2.  Contained in the file specified by the first filename on
  52.               the command line.  (Note that systems supporting the #!
  53.               notation invoke interpreters this way.)
  54.  
  55.           3.  Passed in implicitly via standard input.  This only
  56.               works if there are no filename arguments--to pass
  57.               arguments to a stdin script you must explicitly specify
  58.               a - for the script name.
  59.  
  60.  
  61.  
  62.  
  63.      Page 1                                          (printed 1/17/94)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLL((((1111))))     UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 4444....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  71.  
  72.  
  73.  
  74.           After locating your script, perl compiles it to an internal
  75.           form.  If the script is syntactically correct, it is
  76.           executed.
  77.  
  78.           OOOOppppttttiiiioooonnnnssss
  79.  
  80.           Note: on first reading this section may not make much sense
  81.           to you.  It's here at the front for easy reference.
  82.  
  83.           A single-character option may be combined with the following
  84.           option, if any.  This is particularly useful when invoking a
  85.           script using the #! construct which only allows one
  86.           argument.  Example:
  87.  
  88.                #!/usr/bin/perl -spi.bak # same as -s -p -i.bak
  89.                ...
  90.  
  91.           Options include:
  92.  
  93.           ----0000digits
  94.                specifies the record separator ($/) as an octal number.
  95.                If there are no digits, the null character is the
  96.                separator.  Other switches may precede or follow the
  97.                digits.  For example, if you have a version of find
  98.                which can print filenames terminated by the null
  99.                character, you can say this:
  100.  
  101.                    find . -name '*.bak' -print0 | perl -n0e unlink
  102.  
  103.                The special value 00 will cause Perl to slurp files in
  104.                paragraph mode.  The value 0777 will cause Perl to
  105.                slurp files whole since there is no legal character
  106.                with that value.
  107.  
  108.           ----aaaa   turns on autosplit mode when used with a ----nnnn or ----pppp.  An
  109.                implicit split command to the @F array is done as the
  110.                first thing inside the implicit while loop produced by
  111.                the ----nnnn or ----pppp.
  112.  
  113.                     perl -ane 'print pop(@F), "\n";'
  114.  
  115.                is equivalent to
  116.  
  117.                     while (<>) {
  118.                          @F = split(' ');
  119.                          print pop(@F), "\n";
  120.                     }
  121.  
  122.  
  123.           ----cccc   causes perl to check the syntax of the script and then
  124.                exit without executing it.
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                                          (printed 1/17/94)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLL((((1111))))     UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 4444....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  137.  
  138.  
  139.  
  140.           ----dddd   runs the script under the perl debugger.  See the
  141.                section on Debugging.
  142.  
  143.           ----DDDDnumber
  144.                sets debugging flags.  To watch how it executes your
  145.                script, use ----DDDD11114444.  (This only works if debugging is
  146.                compiled into your perl.)  Another nice value is
  147.                -D1024, which lists your compiled syntax tree.  And
  148.                -D512 displays compiled regular expressions.
  149.  
  150.           ----eeee commandline
  151.                may be used to enter one line of script.  Multiple ----eeee
  152.                commands may be given to build up a multi-line script.
  153.                If ----eeee is given, perl will not look for a script
  154.                filename in the argument list.
  155.  
  156.           ----iiiiextension
  157.                specifies that files processed by the <> construct are
  158.                to be edited in-place.  It does this by renaming the
  159.                input file, opening the output file by the same name,
  160.                and selecting that output file as the default for print
  161.                statements.  The extension, if supplied, is added to
  162.                the name of the old file to make a backup copy.  If no
  163.                extension is supplied, no backup is made.  Saying "perl
  164.                -p -i.bak -e "s/foo/bar/;" ... " is the same as using
  165.                the script:
  166.  
  167.                     #!/usr/bin/perl -pi.bak
  168.                     s/foo/bar/;
  169.  
  170.                which is equivalent to
  171.  
  172.                     #!/usr/bin/perl
  173.                     while (<>) {
  174.                          if ($ARGV ne $oldargv) {
  175.                               rename($ARGV, $ARGV . '.bak');
  176.                               open(ARGVOUT, ">$ARGV");
  177.                               select(ARGVOUT);
  178.                               $oldargv = $ARGV;
  179.                          }
  180.                          s/foo/bar/;
  181.                     }
  182.                     continue {
  183.                         print;     # this prints to original filename
  184.                     }
  185.                     select(STDOUT);
  186.  
  187.                except that the ----iiii form doesn't need to compare $ARGV
  188.                to $oldargv to know when the filename has changed.  It
  189.                does, however, use ARGVOUT for the selected filehandle.
  190.                Note that STDOUT is restored as the default output
  191.                filehandle after the loop.
  192.  
  193.  
  194.  
  195.      Page 3                                          (printed 1/17/94)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLL((((1111))))     UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 4444....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  203.  
  204.  
  205.  
  206.                You can use eof to locate the end of each input file,
  207.                in case you want to append to each file, or reset line
  208.                numbering (see example under eof).
  209.  
  210.           ----IIIIdirectory
  211.                may be used in conjunction with ----PPPP to tell the C
  212.                preprocessor where to look for include files.  By
  213.                default /usr/include and /usr/lib/perl are searched.
  214.  
  215.           ----lllloctnum
  216.                enables automatic line-ending processing.  It has two
  217.                effects: first, it automatically chops the line
  218.                terminator when used with ----nnnn or ----pppp ,,,, and second, it
  219.                assigns $\ to have the value of octnum so that any
  220.                print statements will have that line terminator added
  221.                back on.  If octnum is omitted, sets $\ to the current
  222.                value of $/.  For instance, to trim lines to 80
  223.                columns:
  224.  
  225.                     perl -lpe 'substr($_, 80) = ""'
  226.  
  227.                Note that the assignment $\ = $/ is done when the
  228.                switch is processed, so the input record separator can
  229.                be different than the output record separator if the ----llll
  230.                switch is followed by a ----0000 switch:
  231.  
  232.                     gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  233.  
  234.                This sets $\ to newline and then sets $/ to the null
  235.                character.
  236.  
  237.           ----nnnn   causes perl to assume the following loop around your
  238.                script, which makes it iterate over filename arguments
  239.                somewhat like "sed -n" or awk:
  240.  
  241.                     while (<>) {
  242.                          ...       # your script goes here
  243.                     }
  244.  
  245.                Note that the lines are not printed by default.  See ----pppp
  246.                to have lines printed.  Here is an efficient way to
  247.                delete all files older than a week:
  248.  
  249.                     find . -mtime +7 -print | perl -nle 'unlink;'
  250.  
  251.                This is faster than using the -exec switch of find
  252.                because you don't have to start a process on every
  253.                filename found.
  254.  
  255.           ----pppp   causes perl to assume the following loop around your
  256.                script, which makes it iterate over filename arguments
  257.                somewhat like sed:
  258.  
  259.  
  260.  
  261.      Page 4                                          (printed 1/17/94)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLL((((1111))))     UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 4444....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  269.  
  270.  
  271.  
  272.                     while (<>) {
  273.                          ...       # your script goes here
  274.                     } continue {
  275.                          print;
  276.                     }
  277.  
  278.                Note that the lines are printed automatically.  To
  279.                suppress printing use the ----nnnn switch.  A ----pppp overrides a
  280.                ----nnnn switch.
  281.  
  282.           ----PPPP   causes your script to be run through the C preprocessor
  283.                before compilation by perl.  (Since both comments and
  284.                cpp directives begin with the # character, you should
  285.                avoid starting comments with any words recognized by
  286.                the C preprocessor such as "if", "else" or "define".)
  287.  
  288.           ----ssss   enables some rudimentary switch parsing for switches on
  289.                the command line after the script name but before any
  290.                filename arguments (or before a --).  Any switch found
  291.                there is removed from @ARGV and sets the corresponding
  292.                variable in the perl script.  The following script
  293.                prints "true" if and only if the script is invoked with
  294.                a -xyz switch.
  295.  
  296.                     #!/usr/bin/perl -s
  297.                     if ($xyz) { print "true\n"; }
  298.  
  299.  
  300.           ----SSSS   makes perl use the PATH environment variable to search
  301.                for the script (unless the name of the script starts
  302.                with a slash).  Typically this is used to emulate #!
  303.                startup on machines that don't support #!, in the
  304.                following manner:
  305.  
  306.                     #!/usr/bin/perl
  307.                     eval "exec /usr/bin/perl -S $0 $*"
  308.                          if $running_under_some_shell;
  309.  
  310.                The system ignores the first line and feeds the script
  311.                to /bin/sh, which proceeds to try to execute the perl
  312.                script as a shell script.  The shell executes the
  313.                second line as a normal shell command, and thus starts
  314.                up the perl interpreter.  On some systems $0 doesn't
  315.                always contain the full pathname, so the ----SSSS tells perl
  316.                to search for the script if necessary.  After perl
  317.                locates the script, it parses the lines and ignores
  318.                them because the variable $running_under_some_shell is
  319.                never true.  A better construct than $* would be
  320.                ${1+"$@"}, which handles embedded spaces and such in
  321.                the filenames, but doesn't work if the script is being
  322.                interpreted by csh.  In order to start up sh rather
  323.                than csh, some systems may have to replace the #! line
  324.  
  325.  
  326.  
  327.      Page 5                                          (printed 1/17/94)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLL((((1111))))     UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 4444....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  335.  
  336.  
  337.  
  338.                with a line containing just a colon, which will be
  339.                politely ignored by perl.  Other systems can't control
  340.                that, and need a totally devious construct that will
  341.                work under any of csh, sh or perl, such as the
  342.                following:
  343.  
  344.                     eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  345.                     & eval 'exec /usr/bin/perl -S $0 $argv:q'
  346.                          if 0;
  347.  
  348.  
  349.           ----uuuu   causes perl to dump core after compiling your script.
  350.                You can then take this core dump and turn it into an
  351.                executable file by using the undump program (not
  352.                supplied).  This speeds startup at the expense of some
  353.                disk space (which you can minimize by stripping the
  354.                executable).  (Still, a "hello world" executable comes
  355.                out to about 200K on my machine.)  If you are going to
  356.                run your executable as a set-id program then you should
  357.                probably compile it using taintperl rather than normal
  358.                perl.  If you want to execute a portion of your script
  359.                before dumping, use the dump operator instead.  Note:
  360.                availability of undump is platform specific and may not
  361.                be available for a specific port of perl.
  362.  
  363.           ----UUUU   allows perl to do unsafe operations.  Currently the
  364.                only "unsafe" operations are the unlinking of
  365.                directories while running as superuser, and running
  366.                setuid programs with fatal taint checks turned into
  367.                warnings.
  368.  
  369.           ----vvvv   prints the version and patchlevel of your perl
  370.                executable.
  371.  
  372.           ----wwww   prints warnings about identifiers that are mentioned
  373.                only once, and scalar variables that are used before
  374.                being set.  Also warns about redefined subroutines, and
  375.                references to undefined filehandles or filehandles
  376.                opened readonly that you are attempting to write on.
  377.                Also warns you if you use == on values that don't look
  378.                like numbers, and if your subroutines recurse more than
  379.                100 deep.
  380.  
  381.           ----xxxxdirectory
  382.                tells perl that the script is embedded in a message.
  383.                Leading garbage will be discarded until the first line
  384.                that starts with #! and contains the string "perl".
  385.                Any meaningful switches on that line will be applied
  386.                (but only one group of switches, as with normal #!
  387.                processing).  If a directory name is specified, Perl
  388.                will switch to that directory before running the
  389.                script.  The ----xxxx switch only controls the the disposal
  390.  
  391.  
  392.  
  393.      Page 6                                          (printed 1/17/94)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  401.  
  402.  
  403.  
  404.                of leading garbage.  The script must be terminated with
  405.                __END__ if there is trailing garbage to be ignored (the
  406.                script can process any or all of the trailing garbage
  407.                via the DATA filehandle if desired).
  408.  
  409.           DDDDaaaattttaaaa TTTTyyyyppppeeeessss aaaannnndddd OOOObbbbjjjjeeeeccccttttssss
  410.  
  411.           Perl has three data types: scalars, arrays of scalars, and
  412.           associative arrays of scalars.  Normal arrays are indexed by
  413.           number, and associative arrays by string.
  414.  
  415.           The interpretation of operations and values in perl
  416.           sometimes depends on the requirements of the context around
  417.           the operation or value.  There are three major contexts:
  418.           string, numeric and array.  Certain operations return array
  419.           values in contexts wanting an array, and scalar values
  420.           otherwise.  (If this is true of an operation it will be
  421.           mentioned in the documentation for that operation.)
  422.           Operations which return scalars don't care whether the
  423.           context is looking for a string or a number, but scalar
  424.           variables and values are interpreted as strings or numbers
  425.           as appropriate to the context.  A scalar is interpreted as
  426.           TRUE in the boolean sense if it is not the null string or 0.
  427.           Booleans returned by operators are 1 for true and 0 or ''
  428.           (the null string) for false.
  429.  
  430.           There are actually two varieties of null string: defined and
  431.           undefined.  Undefined null strings are returned when there
  432.           is no real value for something, such as when there was an
  433.           error, or at end of file, or when you refer to an
  434.           uninitialized variable or element of an array.  An undefined
  435.           null string may become defined the first time you access it,
  436.           but prior to that you can use the defined() operator to
  437.           determine whether the value is defined or not.
  438.  
  439.           References to scalar variables always begin with '$', even
  440.           when referring to a scalar that is part of an array.  Thus:
  441.  
  442.               $days           # a simple scalar variable
  443.               $days[28]       # 29th element of array @days
  444.               $days{'Feb'}    # one value from an associative array
  445.               $#days          # last index of array @days
  446.  
  447.           but entire arrays or array slices are denoted by '@':
  448.  
  449.               @days           # ($days[0], $days[1],... $days[n])
  450.               @days[3,4,5]    # same as @days[3..5]
  451.               @days{'a','c'}  # same as ($days{'a'},$days{'c'})
  452.  
  453.           and entire associative arrays are denoted by '%':
  454.  
  455.               %days           # (key1, val1, key2, val2 ...)
  456.  
  457.  
  458.  
  459.      Page 7                                          (printed 1/17/94)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  467.  
  468.  
  469.  
  470.           Any of these eight constructs may serve as an lvalue, that
  471.           is, may be assigned to.  (It also turns out that an
  472.           assignment is itself an lvalue in certain contexts--see
  473.           examples under s, tr and chop.)  Assignment to a scalar
  474.           evaluates the righthand side in a scalar context, while
  475.           assignment to an array or array slice evaluates the
  476.           righthand side in an array context.
  477.  
  478.           You may find the length of array @days by evaluating
  479.           "$#days", as in csh.  (Actually, it's not the length of the
  480.           array, it's the subscript of the last element, since there
  481.           is (ordinarily) a 0th element.)  Assigning to $#days changes
  482.           the length of the array.  Shortening an array by this method
  483.           does not actually destroy any values.  Lengthening an array
  484.           that was previously shortened recovers the values that were
  485.           in those elements.  You can also gain some measure of
  486.           efficiency by preextending an array that is going to get
  487.           big.  (You can also extend an array by assigning to an
  488.           element that is off the end of the array.  This differs from
  489.           assigning to $#whatever in that intervening values are set
  490.           to null rather than recovered.)  You can truncate an array
  491.           down to nothing by assigning the null list () to it.  The
  492.           following are exactly equivalent
  493.  
  494.                @whatever = ();
  495.                $#whatever = $[ - 1;
  496.  
  497.  
  498.           If you evaluate an array in a scalar context, it returns the
  499.           length of the array.  The following is always true:
  500.  
  501.                scalar(@whatever) == $#whatever - $[ + 1;
  502.  
  503.           If you evaluate an associative array in a scalar context, it
  504.           returns a value which is true if and only if the array
  505.           contains any elements.  (If there are any elements, the
  506.           value returned is a string consisting of the number of used
  507.           buckets and the number of allocated buckets, separated by a
  508.           slash.)
  509.  
  510.           Multi-dimensional arrays are not directly supported, but see
  511.           the discussion of the $; variable later for a means of
  512.           emulating multiple subscripts with an associative array.
  513.           You could also write a subroutine to turn multiple
  514.           subscripts into a single subscript.
  515.  
  516.           Every data type has its own namespace.  You can, without
  517.           fear of conflict, use the same name for a scalar variable,
  518.           an array, an associative array, a filehandle, a subroutine
  519.           name, and/or a label.  Since variable and array references
  520.           always start with '$', '@', or '%', the "reserved" words
  521.           aren't in fact reserved with respect to variable names.
  522.  
  523.  
  524.  
  525.      Page 8                                          (printed 1/17/94)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  533.  
  534.  
  535.  
  536.           (They ARE reserved with respect to labels and filehandles,
  537.           however, which don't have an initial special character.
  538.           Hint: you could say open(LOG,'logfile') rather than
  539.           open(log,'logfile').  Using uppercase filehandles also
  540.           improves readability and protects you from conflict with
  541.           future reserved words.)  Case IS significant--"FOO", "Foo"
  542.           and "foo" are all different names.  Names which start with a
  543.           letter may also contain digits and underscores.  Names which
  544.           do not start with a letter are limited to one character,
  545.           e.g. "$%" or "$$".  (Most of the one character names have a
  546.           predefined significance to perl.  More later.)
  547.  
  548.           Numeric literals are specified in any of the usual floating
  549.           point or integer formats:
  550.  
  551.               12345
  552.               12345.67
  553.               .23E-10
  554.               0xffff     # hex
  555.               0377  # octal
  556.               4_294_967_296
  557.  
  558.           String literals are delimited by either single or double
  559.           quotes.  They work much like shell quotes: double-quoted
  560.           string literals are subject to backslash and variable
  561.           substitution; single-quoted strings are not (except for \'
  562.           and \\).  The usual backslash rules apply for making
  563.           characters such as newline, tab, etc., as well as some more
  564.           exotic forms:
  565.  
  566.                \t        tab
  567.                \n        newline
  568.                \r        return
  569.                \f        form feed
  570.                \b        backspace
  571.                \a        alarm (bell)
  572.                \e        escape
  573.                \033      octal char
  574.                \x1b      hex char
  575.                \c[       control char
  576.                \l        lowercase next char
  577.                \u        uppercase next char
  578.                \L        lowercase till \E
  579.                \U        uppercase till \E
  580.                \E        end case modification
  581.  
  582.           You can also embed newlines directly in your strings, i.e.
  583.           they can end on a different line than they begin.  This is
  584.           nice, but if you forget your trailing quote, the error will
  585.           not be reported until perl finds another line containing the
  586.           quote character, which may be much further on in the script.
  587.           Variable substitution inside strings is limited to scalar
  588.  
  589.  
  590.  
  591.      Page 9                                          (printed 1/17/94)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  599.  
  600.  
  601.  
  602.           variables, normal array values, and array slices.  (In other
  603.           words, identifiers beginning with $ or @, followed by an
  604.           optional bracketed expression as a subscript.)  The
  605.           following code segment prints out "The price is $100."
  606.  
  607.               $Price = '$100';               # not interpreted
  608.               print "The price is $Price.\n";# interpreted
  609.  
  610.           Note that you can put curly brackets around the identifier
  611.           to delimit it from following alphanumerics.  Also note that
  612.           a single quoted string must be separated from a preceding
  613.           word by a space, since single quote is a valid character in
  614.           an identifier (see Packages).
  615.  
  616.           Two special literals are __LINE__ and __FILE__, which
  617.           represent the current line number and filename at that point
  618.           in your program.  They may only be used as separate tokens;
  619.           they will not be interpolated into strings.  In addition,
  620.           the token __END__ may be used to indicate the logical end of
  621.           the script before the actual end of file.  Any following
  622.           text is ignored, but may be read via the DATA filehandle.
  623.           (The DATA filehandle may read data only from the main
  624.           script, but not from any required file or evaluated string.)
  625.           The two control characters ^D and ^Z are synonyms for
  626.           __END__.
  627.  
  628.           A word that doesn't have any other interpretation in the
  629.           grammar will be treated as if it had single quotes around
  630.           it.  For this purpose, a word consists only of alphanumeric
  631.           characters and underline, and must start with an alphabetic
  632.           character.  As with filehandles and labels, a bare word that
  633.           consists entirely of lowercase letters risks conflict with
  634.           future reserved words, and if you use the ----wwww switch, Perl
  635.           will warn you about any such words.
  636.  
  637.           Array values are interpolated into double-quoted strings by
  638.           joining all the elements of the array with the delimiter
  639.           specified in the $" variable, space by default.  (Since in
  640.           versions of perl prior to 3.0 the @ character was not a
  641.           metacharacter in double-quoted strings, the interpolation of
  642.           @array, $array[EXPR], @array[LIST], $array{EXPR}, or
  643.           @array{LIST} only happens if array is referenced elsewhere
  644.           in the program or is predefined.)  The following are
  645.           equivalent:
  646.  
  647.                $temp = join($",@ARGV);
  648.                system "echo $temp";
  649.  
  650.                system "echo @ARGV";
  651.  
  652.           Within search patterns (which also undergo double-quotish
  653.           substitution) there is a bad ambiguity:  Is /$foo[bar]/ to
  654.  
  655.  
  656.  
  657.      Page 10                                         (printed 1/17/94)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  665.  
  666.  
  667.  
  668.           be interpreted as /${foo}[bar]/ (where [bar] is a character
  669.           class for the regular expression) or as /${foo[bar]}/ (where
  670.           [bar] is the subscript to array @foo)?  If @foo doesn't
  671.           otherwise exist, then it's obviously a character class.  If
  672.           @foo exists, perl takes a good guess about [bar], and is
  673.           almost always right.  If it does guess wrong, or if you're
  674.           just plain paranoid, you can force the correct
  675.           interpretation with curly brackets as above.
  676.  
  677.           A line-oriented form of quoting is based on the shell here-
  678.           is syntax.  Following a << you specify a string to terminate
  679.           the quoted material, and all lines following the current
  680.           line down to the terminating string are the value of the
  681.           item.  The terminating string may be either an identifier (a
  682.           word), or some quoted text.  If quoted, the type of quotes
  683.           you use determines the treatment of the text, just as in
  684.           regular quoting.  An unquoted identifier works like double
  685.           quotes.  There must be no space between the << and the
  686.           identifier.  (If you put a space it will be treated as a
  687.           null identifier, which is valid, and matches the first blank
  688.           line--see Merry Christmas example below.)  The terminating
  689.           string must appear by itself (unquoted and with no
  690.           surrounding whitespace) on the terminating line.
  691.  
  692.                print <<EOF;        # same as above
  693.           The price is $Price.
  694.           EOF
  695.  
  696.                print <<"EOF";      # same as above
  697.           The price is $Price.
  698.           EOF
  699.  
  700.                print << x 10;      # null identifier is delimiter
  701.           Merry Christmas!
  702.  
  703.                print <<`EOC`;      # execute commands
  704.           echo hi there
  705.           echo lo there
  706.           EOC
  707.  
  708.                print <<foo, <<bar; # you can stack them
  709.           I said foo.
  710.           foo
  711.           I said bar.
  712.           bar
  713.  
  714.           Array literals are denoted by separating individual values
  715.           by commas, and enclosing the list in parentheses:
  716.  
  717.                (LIST)
  718.  
  719.           In a context not requiring an array value, the value of the
  720.  
  721.  
  722.  
  723.      Page 11                                         (printed 1/17/94)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  731.  
  732.  
  733.  
  734.           array literal is the value of the final element, as in the C
  735.           comma operator.  For example,
  736.  
  737.               @foo = ('cc', '-E', $bar);
  738.  
  739.           assigns the entire array value to array foo, but
  740.  
  741.               $foo = ('cc', '-E', $bar);
  742.  
  743.           assigns the value of variable bar to variable foo.  Note
  744.           that the value of an actual array in a scalar context is the
  745.           length of the array; the following assigns to $foo the value
  746.           3:
  747.  
  748.               @foo = ('cc', '-E', $bar);
  749.               $foo = @foo;         # $foo gets 3
  750.  
  751.           You may have an optional comma before the closing
  752.           parenthesis of an array literal, so that you can say:
  753.  
  754.               @foo = (
  755.                1,
  756.                2,
  757.                3,
  758.               );
  759.  
  760.           When a LIST is evaluated, each element of the list is
  761.           evaluated in an array context, and the resulting array value
  762.           is interpolated into LIST just as if each individual element
  763.           were a member of LIST.  Thus arrays lose their identity in a
  764.           LIST--the list
  765.  
  766.                (@foo,@bar,&SomeSub)
  767.  
  768.           contains all the elements of @foo followed by all the
  769.           elements of @bar, followed by all the elements returned by
  770.           the subroutine named SomeSub.
  771.  
  772.           A list value may also be subscripted like a normal array.
  773.           Examples:
  774.  
  775.                $time = (stat($file))[8];     # stat returns array value
  776.                $digit = ('a','b','c','d','e','f')[$digit-10];
  777.                return (pop(@foo),pop(@foo))[0];
  778.  
  779.  
  780.           Array lists may be assigned to if and only if each element
  781.           of the list is an lvalue:
  782.  
  783.               ($a, $b, $c) = (1, 2, 3);
  784.  
  785.               ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  786.  
  787.  
  788.  
  789.      Page 12                                         (printed 1/17/94)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  797.  
  798.  
  799.  
  800.           The final element may be an array or an associative array:
  801.  
  802.               ($a, $b, @rest) = split;
  803.               local($a, $b, %rest) = @_;
  804.  
  805.           You can actually put an array anywhere in the list, but the
  806.           first array in the list will soak up all the values, and
  807.           anything after it will get a null value.  This may be useful
  808.           in a local().
  809.  
  810.           An associative array literal contains pairs of values to be
  811.           interpreted as a key and a value:
  812.  
  813.               # same as map assignment above
  814.               %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  815.  
  816.           Array assignment in a scalar context returns the number of
  817.           elements produced by the expression on the right side of the
  818.           assignment:
  819.  
  820.                $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  821.  
  822.  
  823.           There are several other pseudo-literals that you should know
  824.           about.  If a string is enclosed by backticks (grave
  825.           accents), it first undergoes variable substitution just like
  826.           a double quoted string.  It is then interpreted as a
  827.           command, and the output of that command is the value of the
  828.           pseudo-literal, like in a shell.  In a scalar context, a
  829.           single string consisting of all the output is returned.  In
  830.           an array context, an array of values is returned, one for
  831.           each line of output.  (You can set $/ to use a different
  832.           line terminator.)  The command is executed each time the
  833.           pseudo-literal is evaluated.  The status value of the
  834.           command is returned in $? (see Predefined Names for the
  835.           interpretation of $?).  Unlike in csh, no translation is
  836.           done on the return data--newlines remain newlines.  Unlike
  837.           in any of the shells, single quotes do not hide variable
  838.           names in the command from interpretation.  To pass a $
  839.           through to the shell you need to hide it with a backslash.
  840.  
  841.           Evaluating a filehandle in angle brackets yields the next
  842.           line from that file (newline included, so it's never false
  843.           until EOF, at which time an undefined value is returned).
  844.           Ordinarily you must assign that value to a variable, but
  845.           there is one situation where an automatic assignment
  846.           happens.  If (and only if) the input symbol is the only
  847.           thing inside the conditional of a while loop, the value is
  848.           automatically assigned to the variable "$_".  (This may seem
  849.           like an odd thing to you, but you'll use the construct in
  850.           almost every perl script you write.)  Anyway, the following
  851.           lines are equivalent to each other:
  852.  
  853.  
  854.  
  855.      Page 13                                         (printed 1/17/94)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  863.  
  864.  
  865.  
  866.               while ($_ = <STDIN>) { print; }
  867.               while (<STDIN>) { print; }
  868.               for (;<STDIN>;) { print; }
  869.               print while $_ = <STDIN>;
  870.               print while <STDIN>;
  871.  
  872.           The filehandles STDIN, STDOUT and STDERR are predefined.
  873.           (The filehandles stdin, stdout and stderr will also work
  874.           except in packages, where they would be interpreted as local
  875.           identifiers rather than global.)  Additional filehandles may
  876.           be created with the open function.
  877.  
  878.           If a <FILEHANDLE> is used in a context that is looking for
  879.           an array, an array consisting of all the input lines is
  880.           returned, one line per array element.  It's easy to make a
  881.           LARGE data space this way, so use with care.
  882.  
  883.           The null filehandle <> is special and can be used to emulate
  884.           the behavior of sed and awk.  Input from <> comes either
  885.           from standard input, or from each file listed on the command
  886.           line.  Here's how it works: the first time <> is evaluated,
  887.           the ARGV array is checked, and if it is null, $ARGV[0] is
  888.           set to '-', which when opened gives you standard input.  The
  889.           ARGV array is then processed as a list of filenames.  The
  890.           loop
  891.  
  892.                while (<>) {
  893.                     ...            # code for each line
  894.                }
  895.  
  896.           is equivalent to the following Perl-like pseudo code:
  897.  
  898.                unshift(@ARGV, '-') if $#ARGV < $[;
  899.                while ($ARGV = shift) {
  900.                     open(ARGV, $ARGV);
  901.                     while (<ARGV>) {
  902.                          ...       # code for each line
  903.                     }
  904.                }
  905.  
  906.           except that it isn't as cumbersome to say, and will actually
  907.           work.  It really does shift array ARGV and put the current
  908.           filename into variable ARGV.  It also uses filehandle ARGV
  909.           internally--<> is just a synonym for <ARGV>, which is
  910.           magical.  (The pseudo code above doesn't work because it
  911.           treats <ARGV> as non-magical.)
  912.  
  913.           You can modify @ARGV before the first <> as long as the
  914.           array ends up containing the list of filenames you really
  915.           want.  Line numbers ($.) continue as if the input was one
  916.           big happy file.  (But see example under eof for how to reset
  917.           line numbers on each file.)
  918.  
  919.  
  920.  
  921.      Page 14                                         (printed 1/17/94)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  929.  
  930.  
  931.  
  932.           If you want to set @ARGV to your own list of files, go right
  933.           ahead.  If you want to pass switches into your script, you
  934.           can put a loop on the front like this:
  935.  
  936.                while ($_ = $ARGV[0], /^-/) {
  937.                     shift;
  938.                    last if /^--$/;
  939.                     /^-D(.*)/ && ($debug = $1);
  940.                     /^-v/ && $verbose++;
  941.                     ...       # other switches
  942.                }
  943.                while (<>) {
  944.                     ...       # code for each line
  945.                }
  946.  
  947.           The <> symbol will return FALSE only once.  If you call it
  948.           again after this it will assume you are processing another
  949.           @ARGV list, and if you haven't set @ARGV, will input from
  950.           STDIN.
  951.  
  952.           If the string inside the angle brackets is a reference to a
  953.           scalar variable (e.g. <$foo>), then that variable contains
  954.           the name of the filehandle to input from.
  955.  
  956.           If the string inside angle brackets is not a filehandle, it
  957.           is interpreted as a filename pattern to be globbed, and
  958.           either an array of filenames or the next filename in the
  959.           list is returned, depending on context.  One level of $
  960.           interpretation is done first, but you can't say <$foo>
  961.           because that's an indirect filehandle as explained in the
  962.           previous paragraph.  You could insert curly brackets to
  963.           force interpretation as a filename glob: <${foo}>.  Example:
  964.  
  965.                while (<*.c>) {
  966.                     chmod 0644, $_;
  967.                }
  968.  
  969.           is equivalent to
  970.  
  971.                open(foo, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  972.                while (<foo>) {
  973.                     chop;
  974.                     chmod 0644, $_;
  975.                }
  976.  
  977.           In fact, it's currently implemented that way.  (Which means
  978.           it will not work on filenames with spaces in them unless you
  979.           have /bin/csh on your machine.)  Of course, the shortest way
  980.           to do the above is:
  981.  
  982.                chmod 0644, <*.c>;
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                                         (printed 1/17/94)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  995.  
  996.  
  997.  
  998.           SSSSyyyynnnnttttaaaaxxxx
  999.  
  1000.           A perl script consists of a sequence of declarations and
  1001.           commands.  The only things that need to be declared in perl
  1002.           are report formats and subroutines.  See the sections below
  1003.           for more information on those declarations.  All
  1004.           uninitialized user-created objects are assumed to start with
  1005.           a null or 0 value until they are defined by some explicit
  1006.           operation such as assignment.  The sequence of commands is
  1007.           executed just once, unlike in sed and awk scripts, where the
  1008.           sequence of commands is executed for each input line.  While
  1009.           this means that you must explicitly loop over the lines of
  1010.           your input file (or files), it also means you have much more
  1011.           control over which files and which lines you look at.
  1012.           (Actually, I'm lying--it is possible to do an implicit loop
  1013.           with either the ----nnnn or ----pppp switch.)
  1014.  
  1015.           A declaration can be put anywhere a command can, but has no
  1016.           effect on the execution of the primary sequence of
  1017.           commands--declarations all take effect at compile time.
  1018.           Typically all the declarations are put at the beginning or
  1019.           the end of the script.
  1020.  
  1021.           Perl is, for the most part, a free-form language.  (The only
  1022.           exception to this is format declarations, for fairly obvious
  1023.           reasons.)  Comments are indicated by the # character, and
  1024.           extend to the end of the line.  If you attempt to use /* */
  1025.           C comments, it will be interpreted either as division or
  1026.           pattern matching, depending on the context.  So don't do
  1027.           that.
  1028.  
  1029.           CCCCoooommmmppppoooouuuunnnndddd ssssttttaaaatttteeeemmmmeeeennnnttttssss
  1030.  
  1031.           In perl, a sequence of commands may be treated as one
  1032.           command by enclosing it in curly brackets.  We will call
  1033.           this a BLOCK.
  1034.  
  1035.           The following compound commands may be used to control flow:
  1036.  
  1037.                if (EXPR) BLOCK
  1038.                if (EXPR) BLOCK else BLOCK
  1039.                if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  1040.                LABEL while (EXPR) BLOCK
  1041.                LABEL while (EXPR) BLOCK continue BLOCK
  1042.                LABEL for (EXPR; EXPR; EXPR) BLOCK
  1043.                LABEL foreach VAR (ARRAY) BLOCK
  1044.                LABEL BLOCK continue BLOCK
  1045.  
  1046.           Note that, unlike C and Pascal, these are defined in terms
  1047.           of BLOCKs, not statements.  This means that the curly
  1048.           brackets are required--no dangling statements allowed.  If
  1049.           you want to write conditionals without curly brackets there
  1050.  
  1051.  
  1052.  
  1053.      Page 16                                         (printed 1/17/94)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1061.  
  1062.  
  1063.  
  1064.           are several other ways to do it.  The following all do the
  1065.           same thing:
  1066.  
  1067.                if (!open(foo)) { die "Can't open $foo: $!"; }
  1068.                die "Can't open $foo: $!" unless open(foo);
  1069.                open(foo) || die "Can't open $foo: $!"; # foo or bust!
  1070.                open(foo) ? 'hi mom' : die "Can't open $foo: $!";
  1071.                               # a bit exotic, that last one
  1072.  
  1073.  
  1074.           The if statement is straightforward.  Since BLOCKs are
  1075.           always bounded by curly brackets, there is never any
  1076.           ambiguity about which if an else goes with.  If you use
  1077.           unless in place of if, the sense of the test is reversed.
  1078.  
  1079.           The while statement executes the block as long as the
  1080.           expression is true (does not evaluate to the null string or
  1081.           0).  The LABEL is optional, and if present, consists of an
  1082.           identifier followed by a colon.  The LABEL identifies the
  1083.           loop for the loop control statements next, last, and redo
  1084.           (see below).  If there is a continue BLOCK, it is always
  1085.           executed just before the conditional is about to be
  1086.           evaluated again, similarly to the third part of a for loop
  1087.           in C.  Thus it can be used to increment a loop variable,
  1088.           even when the loop has been continued via the next statement
  1089.           (similar to the C "continue" statement).
  1090.  
  1091.           If the word while is replaced by the word until, the sense
  1092.           of the test is reversed, but the conditional is still tested
  1093.           before the first iteration.
  1094.  
  1095.           In either the if or the while statement, you may replace
  1096.           "(EXPR)" with a BLOCK, and the conditional is true if the
  1097.           value of the last command in that block is true.
  1098.  
  1099.           The for loop works exactly like the corresponding while
  1100.           loop:
  1101.  
  1102.                for ($i = 1; $i < 10; $i++) {
  1103.                     ...
  1104.                }
  1105.  
  1106.           is the same as
  1107.  
  1108.                $i = 1;
  1109.                while ($i < 10) {
  1110.                     ...
  1111.                } continue {
  1112.                     $i++;
  1113.                }
  1114.  
  1115.           The foreach loop iterates over a normal array value and sets
  1116.  
  1117.  
  1118.  
  1119.      Page 17                                         (printed 1/17/94)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1127.  
  1128.  
  1129.  
  1130.           the variable VAR to be each element of the array in turn.
  1131.           The variable is implicitly local to the loop, and regains
  1132.           its former value upon exiting the loop.  The "foreach"
  1133.           keyword is actually identical to the "for" keyword, so you
  1134.           can use "foreach" for readability or "for" for brevity.  If
  1135.           VAR is omitted, $_ is set to each value.  If ARRAY is an
  1136.           actual array (as opposed to an expression returning an array
  1137.           value), you can modify each element of the array by
  1138.           modifying VAR inside the loop.  Examples:
  1139.  
  1140.                for (@ary) { s/foo/bar/; }
  1141.  
  1142.                foreach $elem (@elements) {
  1143.                     $elem *= 2;
  1144.                }
  1145.  
  1146.                for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  1147.                     print $_, "\n"; sleep(1);
  1148.                }
  1149.  
  1150.                for (1..15) { print "Merry Christmas\n"; }
  1151.  
  1152.                foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
  1153.                     print "Item: $item\n";
  1154.                }
  1155.  
  1156.  
  1157.           The BLOCK by itself (labeled or not) is equivalent to a loop
  1158.           that executes once.  Thus you can use any of the loop
  1159.           control statements in it to leave or restart the block.  The
  1160.           continue block is optional.  This construct is particularly
  1161.           nice for doing case structures.
  1162.  
  1163.                foo: {
  1164.                     if (/^abc/) { $abc = 1; last foo; }
  1165.                     if (/^def/) { $def = 1; last foo; }
  1166.                     if (/^xyz/) { $xyz = 1; last foo; }
  1167.                     $nothing = 1;
  1168.                }
  1169.  
  1170.           There is no official switch statement in perl, because there
  1171.           are already several ways to write the equivalent.  In
  1172.           addition to the above, you could write
  1173.  
  1174.                foo: {
  1175.                     $abc = 1, last foo  if /^abc/;
  1176.                     $def = 1, last foo  if /^def/;
  1177.                     $xyz = 1, last foo  if /^xyz/;
  1178.                     $nothing = 1;
  1179.                }
  1180.  
  1181.           or
  1182.  
  1183.  
  1184.  
  1185.      Page 18                                         (printed 1/17/94)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1193.  
  1194.  
  1195.  
  1196.                foo: {
  1197.                     /^abc/ && do { $abc = 1; last foo; };
  1198.                     /^def/ && do { $def = 1; last foo; };
  1199.                     /^xyz/ && do { $xyz = 1; last foo; };
  1200.                     $nothing = 1;
  1201.                }
  1202.  
  1203.           or
  1204.  
  1205.                foo: {
  1206.                     /^abc/ && ($abc = 1, last foo);
  1207.                     /^def/ && ($def = 1, last foo);
  1208.                     /^xyz/ && ($xyz = 1, last foo);
  1209.                     $nothing = 1;
  1210.                }
  1211.  
  1212.           or even
  1213.  
  1214.                if (/^abc/)
  1215.                     { $abc = 1; }
  1216.                elsif (/^def/)
  1217.                     { $def = 1; }
  1218.                elsif (/^xyz/)
  1219.                     { $xyz = 1; }
  1220.                else
  1221.                     {$nothing = 1;}
  1222.  
  1223.           As it happens, these are all optimized internally to a
  1224.           switch structure, so perl jumps directly to the desired
  1225.           statement, and you needn't worry about perl executing a lot
  1226.           of unnecessary statements when you have a string of 50
  1227.           elsifs, as long as you are testing the same simple scalar
  1228.           variable using ==, eq, or pattern matching as above.  (If
  1229.           you're curious as to whether the optimizer has done this for
  1230.           a particular case statement, you can use the -D1024 switch
  1231.           to list the syntax tree before execution.)
  1232.  
  1233.           SSSSiiiimmmmpppplllleeee ssssttttaaaatttteeeemmmmeeeennnnttttssss
  1234.  
  1235.           The only kind of simple statement is an expression evaluated
  1236.           for its side effects.  Every simple statement must be
  1237.           terminated with a semicolon, unless it is the final
  1238.           statement in a block, in which case the semicolon is
  1239.           optional.  (Semicolon is still encouraged there if the block
  1240.           takes up more than one line).
  1241.  
  1242.           Any simple statement may optionally be followed by a single
  1243.           modifier, just before the terminating semicolon.  The
  1244.           possible modifiers are:
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.      Page 19                                         (printed 1/17/94)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1259.  
  1260.  
  1261.  
  1262.                if EXPR
  1263.                unless EXPR
  1264.                while EXPR
  1265.                until EXPR
  1266.  
  1267.           The if and unless modifiers have the expected semantics.
  1268.           The while and until modifiers also have the expected
  1269.           semantics (conditional evaluated first), except when applied
  1270.           to a do-BLOCK or a do-SUBROUTINE command, in which case the
  1271.           block executes once before the conditional is evaluated.
  1272.           This is so that you can write loops like:
  1273.  
  1274.                do {
  1275.                     $_ = <STDIN>;
  1276.                     ...
  1277.                } until $_ eq ".\n";
  1278.  
  1279.           (See the do operator below.  Note also that the loop control
  1280.           commands described later will NOT work in this construct,
  1281.           since modifiers don't take loop labels.  Sorry.)
  1282.  
  1283.           EEEExxxxpppprrrreeeessssssssiiiioooonnnnssss
  1284.  
  1285.           Since perl expressions work almost exactly like C
  1286.           expressions, only the differences will be mentioned here.
  1287.  
  1288.           Here's what perl has that C doesn't:
  1289.  
  1290.           **      The exponentiation operator.
  1291.  
  1292.           **=     The exponentiation assignment operator.
  1293.  
  1294.           ()      The null list, used to initialize an array to null.
  1295.  
  1296.           .       Concatenation of two strings.
  1297.  
  1298.           .=      The concatenation assignment operator.
  1299.  
  1300.           eq      String equality (== is numeric equality).  For a
  1301.                   mnemonic just think of "eq" as a string.  (If you
  1302.                   are used to the awk behavior of using == for either
  1303.                   string or numeric equality based on the current form
  1304.                   of the comparands, beware!  You must be explicit
  1305.                   here.)
  1306.  
  1307.           ne      String inequality (!= is numeric inequality).
  1308.  
  1309.           lt      String less than.
  1310.  
  1311.           gt      String greater than.
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.      Page 20                                         (printed 1/17/94)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1325.  
  1326.  
  1327.  
  1328.           le      String less than or equal.
  1329.  
  1330.           ge      String greater than or equal.
  1331.  
  1332.           cmp     String comparison, returning -1, 0, or 1.
  1333.  
  1334.           <=>     Numeric comparison, returning -1, 0, or 1.
  1335.  
  1336.           =~      Certain operations search or modify the string "$_"
  1337.                   by default.  This operator makes that kind of
  1338.                   operation work on some other string.  The right
  1339.                   argument is a search pattern, substitution, or
  1340.                   translation.  The left argument is what is supposed
  1341.                   to be searched, substituted, or translated instead
  1342.                   of the default "$_".  The return value indicates the
  1343.                   success of the operation.  (If the right argument is
  1344.                   an expression other than a search pattern,
  1345.                   substitution, or translation, it is interpreted as a
  1346.                   search pattern at run time.  This is less efficient
  1347.                   than an explicit search, since the pattern must be
  1348.                   compiled every time the expression is evaluated.)
  1349.                   The precedence of this operator is lower than unary
  1350.                   minus and autoincrement/decrement, but higher than
  1351.                   everything else.
  1352.  
  1353.           !~      Just like =~ except the return value is negated.
  1354.  
  1355.           x       The repetition operator.  Returns a string
  1356.                   consisting of the left operand repeated the number
  1357.                   of times specified by the right operand.  In an
  1358.                   array context, if the left operand is a list in
  1359.                   parens, it repeats the list.
  1360.  
  1361.                        print '-' x 80;          # print row of dashes
  1362.                        print '-' x80;      # illegal, x80 is identifier
  1363.  
  1364.                        print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  1365.  
  1366.                        @ones = (1) x 80;        # an array of 80 1's
  1367.                        @ones = (5) x @ones;          # set all elements to 5
  1368.  
  1369.  
  1370.           x=      The repetition assignment operator.  Only works on
  1371.                   scalars.
  1372.  
  1373.           ..      The range operator, which is really two different
  1374.                   operators depending on the context.  In an array
  1375.                   context, returns an array of values counting (by
  1376.                   ones) from the left value to the right value.  This
  1377.                   is useful for writing "for (1..10)" loops and for
  1378.                   doing slice operations on arrays.
  1379.  
  1380.  
  1381.  
  1382.  
  1383.      Page 21                                         (printed 1/17/94)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1391.  
  1392.  
  1393.  
  1394.                   In a scalar context, .. returns a boolean value.
  1395.                   The operator is bistable, like a flip-flop, and
  1396.                   emulates the line-range (comma) operator of sed,
  1397.                   awk, and various editors.  Each .. operator
  1398.                   maintains its own boolean state.  It is false as
  1399.                   long as its left operand is false.  Once the left
  1400.                   operand is true, the range operator stays true until
  1401.                   the right operand is true, AFTER which the range
  1402.                   operator becomes false again.  (It doesn't become
  1403.                   false till the next time the range operator is
  1404.                   evaluated.  It can test the right operand and become
  1405.                   false on the same evaluation it became true (as in
  1406.                   awk), but it still returns true once.  If you don't
  1407.                   want it to test the right operand till the next
  1408.                   evaluation (as in sed), use three dots (...) instead
  1409.                   of two.)  The right operand is not evaluated while
  1410.                   the operator is in the "false" state, and the left
  1411.                   operand is not evaluated while the operator is in
  1412.                   the "true" state.  The precedence is a little lower
  1413.                   than || and &&.  The value returned is either the
  1414.                   null string for false, or a sequence number
  1415.                   (beginning with 1) for true.  The sequence number is
  1416.                   reset for each range encountered.  The final
  1417.                   sequence number in a range has the string 'E0'
  1418.                   appended to it, which doesn't affect its numeric
  1419.                   value, but gives you something to search for if you
  1420.                   want to exclude the endpoint.  You can exclude the
  1421.                   beginning point by waiting for the sequence number
  1422.                   to be greater than 1.  If either operand of scalar
  1423.                   .. is static, that operand is implicitly compared to
  1424.                   the $. variable, the current line number.  Examples:
  1425.  
  1426.                   As a scalar operator:
  1427.                       if (101 .. 200) { print; }     # print 2nd hundred lines
  1428.  
  1429.                       next line if (1 .. /^$/); # skip header lines
  1430.  
  1431.                       s/^/> / if (/^$/ .. eof());    # quote body
  1432.  
  1433.                   As an array operator:
  1434.                       for (101 .. 200) { print; }    # print $_ 100 times
  1435.  
  1436.                       @foo = @foo[$[ .. $#foo]; # an expensive no-op
  1437.                       @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
  1438.  
  1439.  
  1440.           -x      A file test.  This unary operator takes one
  1441.                   argument, either a filename or a filehandle, and
  1442.                   tests the associated file to see if something is
  1443.                   true about it.  If the argument is omitted, tests
  1444.                   $_, except for -t, which tests STDIN.  It returns 1
  1445.                   for true and '' for false, or the undefined value if
  1446.  
  1447.  
  1448.  
  1449.      Page 22                                         (printed 1/17/94)
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1457.  
  1458.  
  1459.  
  1460.                   the file doesn't exist.  Precedence is higher than
  1461.                   logical and relational operators, but lower than
  1462.                   arithmetic operators.  The operator may be any of:
  1463.                        -r   File is readable by effective uid/gid.
  1464.                        -w   File is writable by effective uid/gid.
  1465.                        -x   File is executable by effective uid/gid.
  1466.                        -o   File is owned by effective uid.
  1467.                        -R   File is readable by real uid/gid.
  1468.                        -W   File is writable by real uid/gid.
  1469.                        -X   File is executable by real uid/gid.
  1470.                        -O   File is owned by real uid.
  1471.                        -e   File exists.
  1472.                        -z   File has zero size.
  1473.                        -s   File has non-zero size (returns size).
  1474.                        -f   File is a plain file.
  1475.                        -d   File is a directory.
  1476.                        -l   File is a symbolic link.
  1477.                        -p   File is a named pipe (FIFO).
  1478.                        -S   File is a socket.
  1479.                        -b   File is a block special file.
  1480.                        -c   File is a character special file.
  1481.                        -u   File has setuid bit set.
  1482.                        -g   File has setgid bit set.
  1483.                        -k   File has sticky bit set.
  1484.                        -t   Filehandle is opened to a tty.
  1485.                        -T   File is a text file.
  1486.                        -B   File is a binary file (opposite of -T).
  1487.                        -M   Age of file in days when script started.
  1488.                        -A   Same for access time.
  1489.                        -C   Same for inode change time.
  1490.  
  1491.                   The interpretation of the file permission operators
  1492.                   -r, -R, -w, -W, -x and -X is based solely on the
  1493.                   mode of the file and the uids and gids of the user.
  1494.                   There may be other reasons you can't actually read,
  1495.                   write or execute the file.  Also note that, for the
  1496.                   superuser, -r, -R, -w and -W always return 1, and -x
  1497.                   and -X return 1 if any execute bit is set in the
  1498.                   mode.  Scripts run by the superuser may thus need to
  1499.                   do a stat() in order to determine the actual mode of
  1500.                   the file, or temporarily set the uid to something
  1501.                   else.
  1502.  
  1503.                   Example:
  1504.  
  1505.                        while (<>) {
  1506.                             chop;
  1507.                             next unless -f $_;  # ignore specials
  1508.                             ...
  1509.                        }
  1510.  
  1511.                   Note that -s/a/b/ does not do a negated
  1512.  
  1513.  
  1514.  
  1515.      Page 23                                         (printed 1/17/94)
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1523.  
  1524.  
  1525.  
  1526.                   substitution.  Saying -exp($foo) still works as
  1527.                   expected, however--only single letters following a
  1528.                   minus are interpreted as file tests.
  1529.  
  1530.                   The -T and -B switches work as follows.  The first
  1531.                   block or so of the file is examined for odd
  1532.                   characters such as strange control codes or
  1533.                   metacharacters.  If too many odd characters (>10%)
  1534.                   are found, it's a -B file, otherwise it's a -T file.
  1535.                   Also, any file containing null in the first block is
  1536.                   considered a binary file.  If -T or -B is used on a
  1537.                   filehandle, the current stdio buffer is examined
  1538.                   rather than the first block.  Both -T and -B return
  1539.                   TRUE on a null file, or a file at EOF when testing a
  1540.                   filehandle.
  1541.  
  1542.           If any of the file tests (or either stat operator) are given
  1543.           the special filehandle consisting of a solitary underline,
  1544.           then the stat structure of the previous file test (or stat
  1545.           operator) is used, saving a system call.  (This doesn't work
  1546.           with -t, and you need to remember that lstat and -l will
  1547.           leave values in the stat structure for the symbolic link,
  1548.           not the real file.)  Example:
  1549.  
  1550.                print "Can do.\n" if -r $a || -w _ || -x _;
  1551.  
  1552.                stat($filename);
  1553.                print "Readable\n" if -r _;
  1554.                print "Writable\n" if -w _;
  1555.                print "Executable\n" if -x _;
  1556.                print "Setuid\n" if -u _;
  1557.                print "Setgid\n" if -g _;
  1558.                print "Sticky\n" if -k _;
  1559.                print "Text\n" if -T _;
  1560.                print "Binary\n" if -B _;
  1561.  
  1562.  
  1563.           Here is what C has that perl doesn't:
  1564.  
  1565.           unary &     Address-of operator.
  1566.  
  1567.           unary *     Dereference-address operator.
  1568.  
  1569.           (TYPE)      Type casting operator.
  1570.  
  1571.           Like C, perl does a certain amount of expression evaluation
  1572.           at compile time, whenever it determines that all of the
  1573.           arguments to an operator are static and have no side
  1574.           effects.  In particular, string concatenation happens at
  1575.           compile time between literals that don't do variable
  1576.           substitution.  Backslash interpretation also happens at
  1577.           compile time.  You can say
  1578.  
  1579.  
  1580.  
  1581.      Page 24                                         (printed 1/17/94)
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1589.  
  1590.  
  1591.  
  1592.                'Now is the time for all' . "\n" .
  1593.                'good men to come to.'
  1594.  
  1595.           and this all reduces to one string internally.
  1596.  
  1597.           The autoincrement operator has a little extra built-in magic
  1598.           to it.  If you increment a variable that is numeric, or that
  1599.           has ever been used in a numeric context, you get a normal
  1600.           increment.  If, however, the variable has only been used in
  1601.           string contexts since it was set, and has a value that is
  1602.           not null and matches the pattern /^[a-zA-Z]*[0-9]*$/, the
  1603.           increment is done as a string, preserving each character
  1604.           within its range, with carry:
  1605.  
  1606.                print ++($foo = '99');   # prints '100'
  1607.                print ++($foo = 'a0');   # prints 'a1'
  1608.                print ++($foo = 'Az');   # prints 'Ba'
  1609.                print ++($foo = 'zz');   # prints 'aaa'
  1610.  
  1611.           The autodecrement is not magical.
  1612.  
  1613.           The range operator (in an array context) makes use of the
  1614.           magical autoincrement algorithm if the minimum and maximum
  1615.           are strings.  You can say
  1616.  
  1617.                @alphabet = ('A' .. 'Z');
  1618.  
  1619.           to get all the letters of the alphabet, or
  1620.  
  1621.                $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  1622.  
  1623.           to get a hexadecimal digit, or
  1624.  
  1625.                @z2 = ('01' .. '31');  print @z2[$mday];
  1626.  
  1627.           to get dates with leading zeros.  (If the final value
  1628.           specified is not in the sequence that the magical increment
  1629.           would produce, the sequence goes until the next value would
  1630.           be longer than the final value specified.)
  1631.  
  1632.           The || and && operators differ from C's in that, rather than
  1633.           returning 0 or 1, they return the last value evaluated.
  1634.           Thus, a portable way to find out the home directory might
  1635.           be:
  1636.  
  1637.                $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1638.                    (getpwuid($<))[7] || die "You're homeless!\n";
  1639.  
  1640.  
  1641.           Along with the literals and variables mentioned earlier, the
  1642.           operations in the following section can serve as terms in an
  1643.           expression.  Some of these operations take a LIST as an
  1644.  
  1645.  
  1646.  
  1647.      Page 25                                         (printed 1/17/94)
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1655.  
  1656.  
  1657.  
  1658.           argument.  Such a list can consist of any combination of
  1659.           scalar arguments or array values; the array values will be
  1660.           included in the list as if each individual element were
  1661.           interpolated at that point in the list, forming a longer
  1662.           single-dimensional array value.  Elements of the LIST should
  1663.           be separated by commas.  If an operation is listed both with
  1664.           and without parentheses around its arguments, it means you
  1665.           can either use it as a unary operator or as a function call.
  1666.           To use it as a function call, the next token on the same
  1667.           line must be a left parenthesis.  (There may be intervening
  1668.           white space.)  Such a function then has highest precedence,
  1669.           as you would expect from a function.  If any token other
  1670.           than a left parenthesis follows, then it is a unary
  1671.           operator, with a precedence depending only on whether it is
  1672.           a LIST operator or not.  LIST operators have lowest
  1673.           precedence.  All other unary operators have a precedence
  1674.           greater than relational operators but less than arithmetic
  1675.           operators.  See the section on Precedence.
  1676.  
  1677.           For operators that can be used in either a scalar or array
  1678.           context, failure is generally indicated in a scalar context
  1679.           by returning the undefined value, and in an array context by
  1680.           returning the null list.  Remember though that THERE IS NO
  1681.           GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR.  Each
  1682.           operator decides which sort of scalar it would be most
  1683.           appropriate to return.  Some operators return the length of
  1684.           the list that would have been returned in an array context.
  1685.           Some operators return the first value in the list.  Some
  1686.           operators return the last value in the list.  Some operators
  1687.           return a count of successful operations.  In general, they
  1688.           do what you want, unless you want consistency.
  1689.  
  1690.           /PATTERN/
  1691.                   See m/PATTERN/.
  1692.  
  1693.           ?PATTERN?
  1694.                   This is just like the /pattern/ search, except that
  1695.                   it matches only once between calls to the reset
  1696.                   operator.  This is a useful optimization when you
  1697.                   only want to see the first occurrence of something
  1698.                   in each file of a set of files, for instance.  Only
  1699.                   ?? patterns local to the current package are reset.
  1700.  
  1701.           accept(NEWSOCKET,GENERICSOCKET)
  1702.                   Does the same thing that the accept system call
  1703.                   does.  Returns true if it succeeded, false
  1704.                   otherwise.  See example in section on Interprocess
  1705.                   Communication.
  1706.  
  1707.           alarm(SECONDS)
  1708.  
  1709.  
  1710.  
  1711.  
  1712.  
  1713.      Page 26                                         (printed 1/17/94)
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1721.  
  1722.  
  1723.  
  1724.           alarm SECONDS
  1725.                   Arranges to have a SIGALRM delivered to this process
  1726.                   after the specified number of seconds (minus 1,
  1727.                   actually) have elapsed.  Thus, alarm(15) will cause
  1728.                   a SIGALRM at some point more than 14 seconds in the
  1729.                   future.  Only one timer may be counting at once.
  1730.                   Each call disables the previous timer, and an
  1731.                   argument of 0 may be supplied to cancel the previous
  1732.                   timer without starting a new one.  The returned
  1733.                   value is the amount of time remaining on the
  1734.                   previous timer.
  1735.  
  1736.           atan2(Y,X)
  1737.                   Returns the arctangent of Y/X in the range -PI to
  1738.                   PI.
  1739.  
  1740.           bind(SOCKET,NAME)
  1741.                   Does the same thing that the bind system call does.
  1742.                   Returns true if it succeeded, false otherwise.  NAME
  1743.                   should be a packed address of the proper type for
  1744.                   the socket.  See example in section on Interprocess
  1745.                   Communication.
  1746.  
  1747.           binmode(FILEHANDLE)
  1748.  
  1749.           binmode FILEHANDLE
  1750.                   Arranges for the file to be read in "binary" mode in
  1751.                   operating systems that distinguish between binary
  1752.                   and text files.  Files that are not read in binary
  1753.                   mode have CR LF sequences translated to LF on input
  1754.                   and LF translated to CR LF on output.  Binmode has
  1755.                   no effect under Unix.  If FILEHANDLE is an
  1756.                   expression, the value is taken as the name of the
  1757.                   filehandle.
  1758.  
  1759.           caller(EXPR)
  1760.  
  1761.           caller  Returns the context of the current subroutine call:
  1762.  
  1763.                        ($package,$filename,$line) = caller;
  1764.  
  1765.                   With EXPR, returns some extra information that the
  1766.                   debugger uses to print a stack trace.  The value of
  1767.                   EXPR indicates how many call frames to go back
  1768.                   before the current one.
  1769.  
  1770.           chdir(EXPR)
  1771.  
  1772.           chdir EXPR
  1773.                   Changes the working directory to EXPR, if possible.
  1774.                   If EXPR is omitted, changes to home directory.
  1775.                   Returns 1 upon success, 0 otherwise.  See example
  1776.  
  1777.  
  1778.  
  1779.      Page 27                                         (printed 1/17/94)
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1787.  
  1788.  
  1789.  
  1790.                   under die.
  1791.  
  1792.           chmod(LIST)
  1793.  
  1794.           chmod LIST
  1795.                   Changes the permissions of a list of files.  The
  1796.                   first element of the list must be the numerical
  1797.                   mode.  Returns the number of files successfully
  1798.                   changed.
  1799.  
  1800.                        $cnt = chmod 0755, 'foo', 'bar';
  1801.                        chmod 0755, @executables;
  1802.  
  1803.  
  1804.           chop(LIST)
  1805.  
  1806.           chop(VARIABLE)
  1807.  
  1808.           chop VARIABLE
  1809.  
  1810.           chop    Chops off the last character of a string and returns
  1811.                   the character chopped.  It's used primarily to
  1812.                   remove the newline from the end of an input record,
  1813.                   but is much more efficient than s/\n// because it
  1814.                   neither scans nor copies the string.  If VARIABLE is
  1815.                   omitted, chops $_.  Example:
  1816.  
  1817.                        while (<>) {
  1818.                             chop;     # avoid \n on last field
  1819.                             @array = split(/:/);
  1820.                             ...
  1821.                        }
  1822.  
  1823.                   You can actually chop anything that's an lvalue,
  1824.                   including an assignment:
  1825.  
  1826.                        chop($cwd = `pwd`);
  1827.                        chop($answer = <STDIN>);
  1828.  
  1829.                   If you chop a list, each element is chopped.  Only
  1830.                   the value of the last chop is returned.
  1831.  
  1832.           chown(LIST)
  1833.  
  1834.           chown LIST
  1835.                   Changes the owner (and group) of a list of files.
  1836.                   The first two elements of the list must be the
  1837.                   NUMERICAL uid and gid, in that order.  Returns the
  1838.                   number of files successfully changed.
  1839.  
  1840.                        $cnt = chown $uid, $gid, 'foo', 'bar';
  1841.                        chown $uid, $gid, @filenames;
  1842.  
  1843.  
  1844.  
  1845.      Page 28                                         (printed 1/17/94)
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1853.  
  1854.  
  1855.  
  1856.                   Here's an example that looks up non-numeric uids in
  1857.                   the passwd file:
  1858.  
  1859.                        print "User: ";
  1860.                        $user = <STDIN>;
  1861.                        chop($user);
  1862.                        print "Files: "
  1863.                        $pattern = <STDIN>;
  1864.                        chop($pattern);
  1865.                        open(pass, '/etc/passwd')
  1866.                             || die "Can't open passwd: $!\n";
  1867.                        while (<pass>) {
  1868.                             ($login,$pass,$uid,$gid) = split(/:/);
  1869.                             $uid{$login} = $uid;
  1870.                             $gid{$login} = $gid;
  1871.                        }
  1872.                        @ary = <${pattern}>;     # get filenames
  1873.                        if ($uid{$user} eq '') {
  1874.                             die "$user not in passwd file";
  1875.                        }
  1876.                        else {
  1877.                             chown $uid{$user}, $gid{$user}, @ary;
  1878.                        }
  1879.  
  1880.  
  1881.           chroot(FILENAME)
  1882.  
  1883.           chroot FILENAME
  1884.                   Does the same as the system call of that name.  If
  1885.                   you don't know what it does, don't worry about it.
  1886.                   If FILENAME is omitted, does chroot to $_.
  1887.  
  1888.           close(FILEHANDLE)
  1889.  
  1890.           close FILEHANDLE
  1891.                   Closes the file or pipe associated with the file
  1892.                   handle.  You don't have to close FILEHANDLE if you
  1893.                   are immediately going to do another open on it,
  1894.                   since open will close it for you.  (See open.)
  1895.                   However, an explicit close on an input file resets
  1896.                   the line counter ($.), while the implicit close done
  1897.                   by open does not.  Also, closing a pipe will wait
  1898.                   for the process executing on the pipe to complete,
  1899.                   in case you want to look at the output of the pipe
  1900.                   afterwards.  Closing a pipe explicitly also puts the
  1901.                   status value of the command into $?.  Example:
  1902.  
  1903.                        open(OUTPUT, '|sort >foo');   # pipe to sort
  1904.                        ...  # print stuff to output
  1905.                        close OUTPUT;       # wait for sort to finish
  1906.                        open(INPUT, 'foo'); # get sort's results
  1907.  
  1908.  
  1909.  
  1910.  
  1911.      Page 29                                         (printed 1/17/94)
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1919.  
  1920.  
  1921.  
  1922.                   FILEHANDLE may be an expression whose value gives
  1923.                   the real filehandle name.
  1924.  
  1925.           closedir(DIRHANDLE)
  1926.  
  1927.           closedir DIRHANDLE
  1928.                   Closes a directory opened by opendir().
  1929.  
  1930.           connect(SOCKET,NAME)
  1931.                   Does the same thing that the connect system call
  1932.                   does.  Returns true if it succeeded, false
  1933.                   otherwise.  NAME should be a package address of the
  1934.                   proper type for the socket.  See example in section
  1935.                   on Interprocess Communication.
  1936.  
  1937.           cos(EXPR)
  1938.  
  1939.           cos EXPR
  1940.                   Returns the cosine of EXPR (expressed in radians).
  1941.                   If EXPR is omitted takes cosine of $_.
  1942.  
  1943.           crypt(PLAINTEXT,SALT)
  1944.                   Encrypts a string exactly like the crypt() function
  1945.                   in the C library.  Useful for checking the password
  1946.                   file for lousy passwords.  Only the guys wearing
  1947.                   white hats should do this.
  1948.  
  1949.           dbmclose(ASSOC_ARRAY)
  1950.  
  1951.           dbmclose ASSOC_ARRAY
  1952.                   Breaks the binding between a dbm file and an
  1953.                   associative array.  The values remaining in the
  1954.                   associative array are meaningless unless you happen
  1955.                   to want to know what was in the cache for the dbm
  1956.                   file.  This function is only useful if you have
  1957.                   ndbm.
  1958.  
  1959.           dbmopen(ASSOC,DBNAME,MODE)
  1960.                   This binds a dbm or ndbm file to an associative
  1961.                   array.  ASSOC is the name of the associative array.
  1962.                   (Unlike normal open, the first argument is NOT a
  1963.                   filehandle, even though it looks like one).  DBNAME
  1964.                   is the name of the database (without the .dir or
  1965.                   .pag extension).  If the database does not exist, it
  1966.                   is created with protection specified by MODE (as
  1967.                   modified by the umask).  If your system only
  1968.                   supports the older dbm functions, you may perform
  1969.                   only one dbmopen in your program.  If your system
  1970.                   has neither dbm nor ndbm, calling dbmopen produces a
  1971.                   fatal error.
  1972.  
  1973.                   Values assigned to the associative array prior to
  1974.  
  1975.  
  1976.  
  1977.      Page 30                                         (printed 1/17/94)
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  1985.  
  1986.  
  1987.  
  1988.                   the dbmopen are lost.  A certain number of values
  1989.                   from the dbm file are cached in memory.  By default
  1990.                   this number is 64, but you can increase it by
  1991.                   preallocating that number of garbage entries in the
  1992.                   associative array before the dbmopen.  You can flush
  1993.                   the cache if necessary with the reset command.
  1994.  
  1995.                   If you don't have write access to the dbm file, you
  1996.                   can only read associative array variables, not set
  1997.                   them.  If you want to test whether you can write,
  1998.                   either use file tests or try setting a dummy array
  1999.                   entry inside an eval, which will trap the error.
  2000.  
  2001.                   Note that functions such as keys() and values() may
  2002.                   return huge array values when used on large dbm
  2003.                   files.  You may prefer to use the each() function to
  2004.                   iterate over large dbm files.  Example:
  2005.  
  2006.                        # print out history file offsets
  2007.                        dbmopen(HIST,'/usr/lib/news/history',0666);
  2008.                        while (($key,$val) = each %HIST) {
  2009.                             print $key, ' = ', unpack('L',$val), "\n";
  2010.                        }
  2011.                        dbmclose(HIST);
  2012.  
  2013.  
  2014.           defined(EXPR)
  2015.  
  2016.           defined EXPR
  2017.                   Returns a boolean value saying whether the lvalue
  2018.                   EXPR has a real value or not.  Many operations
  2019.                   return the undefined value under exceptional
  2020.                   conditions, such as end of file, uninitialized
  2021.                   variable, system error and such.  This function
  2022.                   allows you to distinguish between an undefined null
  2023.                   string and a defined null string with operations
  2024.                   that might return a real null string, in particular
  2025.                   referencing elements of an array.  You may also
  2026.                   check to see if arrays or subroutines exist.  Use on
  2027.                   predefined variables is not guaranteed to produce
  2028.                   intuitive results.  Examples:
  2029.  
  2030.                        print if defined $switch{'D'};
  2031.                        print "$val\n" while defined($val = pop(@ary));
  2032.                        die "Can't readlink $sym: $!"
  2033.                             unless defined($value = readlink $sym);
  2034.                        eval '@foo = ()' if defined(@foo);
  2035.                        die "No XYZ package defined" unless defined %_XYZ;
  2036.                        sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  2037.  
  2038.                   See also undef.
  2039.  
  2040.  
  2041.  
  2042.  
  2043.      Page 31                                         (printed 1/17/94)
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2051.  
  2052.  
  2053.  
  2054.           delete $ASSOC{KEY}
  2055.                   Deletes the specified value from the specified
  2056.                   associative array.  Returns the deleted value, or
  2057.                   the undefined value if nothing was deleted.
  2058.                   Deleting from $ENV{} modifies the environment.
  2059.                   Deleting from an array bound to a dbm file deletes
  2060.                   the entry from the dbm file.
  2061.  
  2062.                   The following deletes all the values of an
  2063.                   associative array:
  2064.  
  2065.                        foreach $key (keys %ARRAY) {
  2066.                             delete $ARRAY{$key};
  2067.                        }
  2068.  
  2069.                   (But it would be faster to use the reset command.
  2070.                   Saying undef %ARRAY is faster yet.)
  2071.  
  2072.           die(LIST)
  2073.  
  2074.           die LIST
  2075.                   Outside of an eval, prints the value of LIST to
  2076.                   STDERR and exits with the current value of $!
  2077.                   (errno).  If $! is 0, exits with the value of ($? >>
  2078.                   8) (`command` status).  If ($? >> 8) is 0, exits
  2079.                   with 255.  Inside an eval, the error message is
  2080.                   stuffed into $@ and the eval is terminated with the
  2081.                   undefined value.
  2082.  
  2083.                   Equivalent examples:
  2084.  
  2085.                        die "Can't cd to spool: $!\n"
  2086.                             unless chdir '/usr/spool/news';
  2087.  
  2088.                        chdir '/usr/spool/news' || die "Can't cd to spool: $!\n"
  2089.  
  2090.  
  2091.                   If the value of EXPR does not end in a newline, the
  2092.                   current script line number and input line number (if
  2093.                   any) are also printed, and a newline is supplied.
  2094.                   Hint: sometimes appending ", stopped" to your
  2095.                   message will cause it to make better sense when the
  2096.                   string "at foo line 123" is appended.  Suppose you
  2097.                   are running script "canasta".
  2098.  
  2099.                        die "/etc/games is no good";
  2100.                        die "/etc/games is no good, stopped";
  2101.  
  2102.                   produce, respectively
  2103.  
  2104.                        /etc/games is no good at canasta line 123.
  2105.                        /etc/games is no good, stopped at canasta line 123.
  2106.  
  2107.  
  2108.  
  2109.      Page 32                                         (printed 1/17/94)
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2117.  
  2118.  
  2119.  
  2120.                   See also exit.
  2121.  
  2122.           do BLOCK
  2123.                   Returns the value of the last command in the
  2124.                   sequence of commands indicated by BLOCK.  When
  2125.                   modified by a loop modifier, executes the BLOCK once
  2126.                   before testing the loop condition.  (On other
  2127.                   statements the loop modifiers test the conditional
  2128.                   first.)
  2129.  
  2130.           do SUBROUTINE (LIST)
  2131.                   Executes a SUBROUTINE declared by a sub declaration,
  2132.                   and returns the value of the last expression
  2133.                   evaluated in SUBROUTINE.  If there is no subroutine
  2134.                   by that name, produces a fatal error.  (You may use
  2135.                   the "defined" operator to determine if a subroutine
  2136.                   exists.)  If you pass arrays as part of LIST you may
  2137.                   wish to pass the length of the array in front of
  2138.                   each array.  (See the section on subroutines later
  2139.                   on.)  The parentheses are required to avoid
  2140.                   confusion with the "do EXPR" form.
  2141.  
  2142.                   SUBROUTINE may also be a single scalar variable, in
  2143.                   which case the name of the subroutine to execute is
  2144.                   taken from the variable.
  2145.  
  2146.                   As an alternate (and preferred) form, you may call a
  2147.                   subroutine by prefixing the name with an ampersand:
  2148.                   &foo(@args).  If you aren't passing any arguments,
  2149.                   you don't have to use parentheses.  If you omit the
  2150.                   parentheses, no @_ array is passed to the
  2151.                   subroutine.  The & form is also used to specify
  2152.                   subroutines to the defined and undef operators:
  2153.  
  2154.                        if (defined &$var) { &$var($parm); undef &$var; }
  2155.  
  2156.  
  2157.           do EXPR Uses the value of EXPR as a filename and executes
  2158.                   the contents of the file as a perl script.  Its
  2159.                   primary use is to include subroutines from a perl
  2160.                   subroutine library.
  2161.  
  2162.                        do 'stat.pl';
  2163.  
  2164.                   is just like
  2165.  
  2166.                        eval `cat stat.pl`;
  2167.  
  2168.                   except that it's more efficient, more concise, keeps
  2169.                   track of the current filename for error messages,
  2170.                   and searches all the ----IIII libraries if the file isn't
  2171.                   in the current directory (see also the @INC array in
  2172.  
  2173.  
  2174.  
  2175.      Page 33                                         (printed 1/17/94)
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2183.  
  2184.  
  2185.  
  2186.                   Predefined Names).  It's the same, however, in that
  2187.                   it does reparse the file every time you call it, so
  2188.                   if you are going to use the file inside a loop you
  2189.                   might prefer to use -P and #include, at the expense
  2190.                   of a little more startup time.  (The main problem
  2191.                   with #include is that cpp doesn't grok # comments--a
  2192.                   workaround is to use ";#" for standalone comments.)
  2193.                   Note that the following are NOT equivalent:
  2194.  
  2195.                        do $foo;  # eval a file
  2196.                        do $foo();     # call a subroutine
  2197.  
  2198.                   Note that inclusion of library routines is better
  2199.                   done with the "require" operator.
  2200.  
  2201.           dump LABEL
  2202.                   This causes an immediate core dump.  Primarily this
  2203.                   is so that you can use the undump program to turn
  2204.                   your core dump into an executable binary after
  2205.                   having initialized all your variables at the
  2206.                   beginning of the program.  When the new binary is
  2207.                   executed it will begin by executing a "goto LABEL"
  2208.                   (with all the restrictions that goto suffers).
  2209.                   Think of it as a goto with an intervening core dump
  2210.                   and reincarnation.  If LABEL is omitted, restarts
  2211.                   the program from the top.  WARNING: any files opened
  2212.                   at the time of the dump will NOT be open any more
  2213.                   when the program is reincarnated, with possible
  2214.                   resulting confusion on the part of perl.  See also
  2215.                   -u.
  2216.  
  2217.                   Example:
  2218.  
  2219.                        #!/usr/bin/perl
  2220.                        require 'getopt.pl';
  2221.                        require 'stat.pl';
  2222.                        %days = (
  2223.                            'Sun',1,
  2224.                            'Mon',2,
  2225.                            'Tue',3,
  2226.                            'Wed',4,
  2227.                            'Thu',5,
  2228.                            'Fri',6,
  2229.                            'Sat',7);
  2230.  
  2231.                        dump QUICKSTART if $ARGV[0] eq '-d';
  2232.  
  2233.                       QUICKSTART:
  2234.                        do Getopt('f');
  2235.  
  2236.  
  2237.  
  2238.  
  2239.  
  2240.  
  2241.      Page 34                                         (printed 1/17/94)
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2249.  
  2250.  
  2251.  
  2252.           each(ASSOC_ARRAY)
  2253.  
  2254.           each ASSOC_ARRAY
  2255.                   Returns a 2 element array consisting of the key and
  2256.                   value for the next value of an associative array, so
  2257.                   that you can iterate over it.  Entries are returned
  2258.                   in an apparently random order.  When the array is
  2259.                   entirely read, a null array is returned (which when
  2260.                   assigned produces a FALSE (0) value).  The next call
  2261.                   to each() after that will start iterating again.
  2262.                   The iterator can be reset only by reading all the
  2263.                   elements from the array.  You must not modify the
  2264.                   array while iterating over it.  There is a single
  2265.                   iterator for each associative array, shared by all
  2266.                   each(), keys() and values() function calls in the
  2267.                   program.  The following prints out your environment
  2268.                   like the printenv program, only in a different
  2269.                   order:
  2270.  
  2271.                        while (($key,$value) = each %ENV) {
  2272.                             print "$key=$value\n";
  2273.                        }
  2274.  
  2275.                   See also keys() and values().
  2276.  
  2277.           eof(FILEHANDLE)
  2278.  
  2279.           eof()
  2280.  
  2281.           eof     Returns 1 if the next read on FILEHANDLE will return
  2282.                   end of file, or if FILEHANDLE is not open.
  2283.                   FILEHANDLE may be an expression whose value gives
  2284.                   the real filehandle name.  (Note that this function
  2285.                   actually reads a character and then ungetc's it, so
  2286.                   it is not very useful in an interactive context.)
  2287.                   An eof without an argument returns the eof status
  2288.                   for the last file read.  Empty parentheses () may be
  2289.                   used to indicate the pseudo file formed of the files
  2290.                   listed on the command line, i.e. eof() is reasonable
  2291.                   to use inside a while (<>) loop to detect the end of
  2292.                   only the last file.  Use eof(ARGV) or eof without
  2293.                   the parentheses to test EACH file in a while (<>)
  2294.                   loop.  Examples:
  2295.  
  2296.                        # insert dashes just before last line of last file
  2297.                        while (<>) {
  2298.                             if (eof()) {
  2299.                                  print "--------------\n";
  2300.                             }
  2301.                             print;
  2302.                        }
  2303.  
  2304.  
  2305.  
  2306.  
  2307.      Page 35                                         (printed 1/17/94)
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2315.  
  2316.  
  2317.  
  2318.                        # reset line numbering on each input file
  2319.                        while (<>) {
  2320.                             print "$.\t$_";
  2321.                             if (eof) {     # Not eof().
  2322.                                  close(ARGV);
  2323.                             }
  2324.                        }
  2325.  
  2326.  
  2327.           eval(EXPR)
  2328.  
  2329.           eval EXPR
  2330.  
  2331.           eval BLOCK
  2332.                   EXPR is parsed and executed as if it were a little
  2333.                   perl program.  It is executed in the context of the
  2334.                   current perl program, so that any variable settings,
  2335.                   subroutine or format definitions remain afterwards.
  2336.                   The value returned is the value of the last
  2337.                   expression evaluated, just as with subroutines.  If
  2338.                   there is a syntax error or runtime error, or a die
  2339.                   statement is executed, an undefined value is
  2340.                   returned by eval, and $@ is set to the error
  2341.                   message.  If there was no error, $@ is guaranteed to
  2342.                   be a null string.  If EXPR is omitted, evaluates $_.
  2343.                   The final semicolon, if any, may be omitted from the
  2344.                   expression.
  2345.  
  2346.                   Note that, since eval traps otherwise-fatal errors,
  2347.                   it is useful for determining whether a particular
  2348.                   feature (such as dbmopen or symlink) is implemented.
  2349.                   It is also Perl's exception trapping mechanism,
  2350.                   where the die operator is used to raise exceptions.
  2351.  
  2352.                   If the code to be executed doesn't vary, you may use
  2353.                   the eval-BLOCK form to trap run-time errors without
  2354.                   incurring the penalty of recompiling each time.  The
  2355.                   error, if any, is still returned in $@.  Evaluating
  2356.                   a single-quoted string (as EXPR) has the same
  2357.                   effect, except that the eval-EXPR form reports
  2358.                   syntax errors at run time via $@, whereas the eval-
  2359.                   BLOCK form reports syntax errors at compile time.
  2360.                   The eval-EXPR form is optimized to eval-BLOCK the
  2361.                   first time it succeeds.  (Since the replacement side
  2362.                   of a substitution is considered a single-quoted
  2363.                   string when you use the e modifier, the same
  2364.                   optimization occurs there.)  Examples:
  2365.  
  2366.  
  2367.  
  2368.  
  2369.  
  2370.  
  2371.  
  2372.  
  2373.      Page 36                                         (printed 1/17/94)
  2374.  
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2381.  
  2382.  
  2383.  
  2384.                        # make divide-by-zero non-fatal
  2385.                        eval { $answer = $a / $b; }; warn $@ if $@;
  2386.  
  2387.                        # optimized to same thing after first use
  2388.                        eval '$answer = $a / $b'; warn $@ if $@;
  2389.  
  2390.                        # a compile-time error
  2391.                        eval { $answer = };
  2392.  
  2393.                        # a run-time error
  2394.                        eval '$answer =';   # sets $@
  2395.  
  2396.  
  2397.           exec(LIST)
  2398.  
  2399.           exec LIST
  2400.                   If there is more than one argument in LIST, or if
  2401.                   LIST is an array with more than one value, calls
  2402.                   execvp() with the arguments in LIST.  If there is
  2403.                   only one scalar argument, the argument is checked
  2404.                   for shell metacharacters.  If there are any, the
  2405.                   entire argument is passed to "/bin/sh -c" for
  2406.                   parsing.  If there are none, the argument is split
  2407.                   into words and passed directly to execvp(), which is
  2408.                   more efficient.  Note: exec (and system) do not
  2409.                   flush your output buffer, so you may need to set $|
  2410.                   to avoid lost output.  Examples:
  2411.  
  2412.                        exec '/bin/echo', 'Your arguments are: ', @ARGV;
  2413.                        exec "sort $outfile | uniq";
  2414.  
  2415.  
  2416.                   If you don't really want to execute the first
  2417.                   argument, but want to lie to the program you are
  2418.                   executing about its own name, you can specify the
  2419.                   program you actually want to run by assigning that
  2420.                   to a variable and putting the name of the variable
  2421.                   in front of the LIST without a comma.  (This always
  2422.                   forces interpretation of the LIST as a multi-valued
  2423.                   list, even if there is only a single scalar in the
  2424.                   list.)  Example:
  2425.  
  2426.                        $shell = '/bin/csh';
  2427.                        exec $shell '-sh';       # pretend it's a login shell
  2428.  
  2429.  
  2430.           exit(EXPR)
  2431.  
  2432.           exit EXPR
  2433.                   Evaluates EXPR and exits immediately with that
  2434.                   value.  Example:
  2435.  
  2436.  
  2437.  
  2438.  
  2439.      Page 37                                         (printed 1/17/94)
  2440.  
  2441.  
  2442.  
  2443.  
  2444.  
  2445.  
  2446.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2447.  
  2448.  
  2449.  
  2450.                        $ans = <STDIN>;
  2451.                        exit 0 if $ans =~ /^[Xx]/;
  2452.  
  2453.                   See also die.  If EXPR is omitted, exits with 0
  2454.                   status.
  2455.  
  2456.           exp(EXPR)
  2457.  
  2458.           exp EXPR
  2459.                   Returns e to the power of EXPR.  If EXPR is omitted,
  2460.                   gives exp($_).
  2461.  
  2462.           fcntl(FILEHANDLE,FUNCTION,SCALAR)
  2463.                   Implements the fcntl(2) function.  You'll probably
  2464.                   have to say
  2465.  
  2466.                        require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
  2467.  
  2468.                   first to get the correct function definitions.  If
  2469.                   fcntl.ph doesn't exist or doesn't have the correct
  2470.                   definitions you'll have to roll your own, based on
  2471.                   your C header files such as <sys/fcntl.h>.  (There
  2472.                   is a perl script called h2ph that comes with the
  2473.                   perl kit which may help you in this.)  Argument
  2474.                   processing and value return works just like ioctl
  2475.                   below.  Note that fcntl will produce a fatal error
  2476.                   if used on a machine that doesn't implement
  2477.                   fcntl(2).
  2478.  
  2479.           fileno(FILEHANDLE)
  2480.  
  2481.           fileno FILEHANDLE
  2482.                   Returns the file descriptor for a filehandle.
  2483.                   Useful for constructing bitmaps for select().  If
  2484.                   FILEHANDLE is an expression, the value is taken as
  2485.                   the name of the filehandle.
  2486.  
  2487.           flock(FILEHANDLE,OPERATION)
  2488.                   Calls flock(2) on FILEHANDLE.  See manual page for
  2489.                   flock(2) for definition of OPERATION.  Returns true
  2490.                   for success, false on failure.  Will produce a fatal
  2491.                   error if used on a machine that doesn't implement
  2492.                   flock(2).  Here's a mailbox appender for BSD
  2493.                   systems.
  2494.  
  2495.  
  2496.  
  2497.  
  2498.  
  2499.  
  2500.  
  2501.  
  2502.  
  2503.  
  2504.  
  2505.      Page 38                                         (printed 1/17/94)
  2506.  
  2507.  
  2508.  
  2509.  
  2510.  
  2511.  
  2512.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2513.  
  2514.  
  2515.  
  2516.                        $LOCK_SH = 1;
  2517.                        $LOCK_EX = 2;
  2518.                        $LOCK_NB = 4;
  2519.                        $LOCK_UN = 8;
  2520.  
  2521.                        sub lock {
  2522.                            flock(MBOX,$LOCK_EX);
  2523.                            # and, in case someone appended
  2524.                            # while we were waiting...
  2525.                            seek(MBOX, 0, 2);
  2526.                        }
  2527.  
  2528.                        sub unlock {
  2529.                            flock(MBOX,$LOCK_UN);
  2530.                        }
  2531.  
  2532.                        open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  2533.                             || die "Can't open mailbox: $!";
  2534.  
  2535.                        do lock();
  2536.                        print MBOX $msg,"\n\n";
  2537.                        do unlock();
  2538.  
  2539.  
  2540.           fork    Does a fork() call.  Returns the child pid to the
  2541.                   parent process and 0 to the child process.  Note:
  2542.                   unflushed buffers remain unflushed in both
  2543.                   processes, which means you may need to set $| to
  2544.                   avoid duplicate output.
  2545.  
  2546.           getc(FILEHANDLE)
  2547.  
  2548.           getc FILEHANDLE
  2549.  
  2550.           getc    Returns the next character from the input file
  2551.                   attached to FILEHANDLE, or a null string at EOF.  If
  2552.                   FILEHANDLE is omitted, reads from STDIN.
  2553.  
  2554.           getlogin
  2555.                   Returns the current login from /etc/utmp, if any.
  2556.                   If null, use getpwuid.
  2557.  
  2558.                        $login = getlogin || (getpwuid($<))[0] ||
  2559.                   "Somebody";
  2560.  
  2561.  
  2562.           getpeername(SOCKET)
  2563.                   Returns the packed sockaddr address of other end of
  2564.                   the SOCKET connection.
  2565.  
  2566.  
  2567.  
  2568.  
  2569.  
  2570.  
  2571.      Page 39                                         (printed 1/17/94)
  2572.  
  2573.  
  2574.  
  2575.  
  2576.  
  2577.  
  2578.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2579.  
  2580.  
  2581.  
  2582.                        # An internet sockaddr
  2583.                        $sockaddr = 'S n a4 x8';
  2584.                        $hersockaddr = getpeername(S);
  2585.                        ($family, $port, $heraddr) =
  2586.                                  unpack($sockaddr,$hersockaddr);
  2587.  
  2588.  
  2589.           getpgrp(PID)
  2590.  
  2591.           getpgrp PID
  2592.                   Returns the current process group for the specified
  2593.                   PID, 0 for the current process.  Will produce a
  2594.                   fatal error if used on a machine that doesn't
  2595.                   implement getpgrp(2).  If EXPR is omitted, returns
  2596.                   process group of current process.
  2597.  
  2598.           getppid Returns the process id of the parent process.
  2599.  
  2600.           getpriority(WHICH,WHO)
  2601.                   Returns the current priority for a process, a
  2602.                   process group, or a user.  (See getpriority(2).)
  2603.                   Will produce a fatal error if used on a machine that
  2604.                   doesn't implement getpriority(2).
  2605.  
  2606.           getpwnam(NAME)
  2607.  
  2608.           getgrnam(NAME)
  2609.  
  2610.           gethostbyname(NAME)
  2611.  
  2612.           getnetbyname(NAME)
  2613.  
  2614.           getprotobyname(NAME)
  2615.  
  2616.           getpwuid(UID)
  2617.  
  2618.           getgrgid(GID)
  2619.  
  2620.           getservbyname(NAME,PROTO)
  2621.  
  2622.           gethostbyaddr(ADDR,ADDRTYPE)
  2623.  
  2624.           getnetbyaddr(ADDR,ADDRTYPE)
  2625.  
  2626.           getprotobynumber(NUMBER)
  2627.  
  2628.           getservbyport(PORT,PROTO)
  2629.  
  2630.           getpwent
  2631.  
  2632.           getgrent
  2633.  
  2634.  
  2635.  
  2636.  
  2637.      Page 40                                         (printed 1/17/94)
  2638.  
  2639.  
  2640.  
  2641.  
  2642.  
  2643.  
  2644.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2645.  
  2646.  
  2647.  
  2648.           gethostent
  2649.  
  2650.           getnetent
  2651.  
  2652.           getprotoent
  2653.  
  2654.           getservent
  2655.  
  2656.           setpwent
  2657.  
  2658.           setgrent
  2659.  
  2660.           sethostent(STAYOPEN)
  2661.  
  2662.           setnetent(STAYOPEN)
  2663.  
  2664.           setprotoent(STAYOPEN)
  2665.  
  2666.           setservent(STAYOPEN)
  2667.  
  2668.           endpwent
  2669.  
  2670.           endgrent
  2671.  
  2672.           endhostent
  2673.  
  2674.           endnetent
  2675.  
  2676.           endprotoent
  2677.  
  2678.           endservent
  2679.                   These routines perform the same functions as their
  2680.                   counterparts in the system library.  Within an array
  2681.                   context, the return values from the various get
  2682.                   routines are as follows:
  2683.  
  2684.                        ($name,$passwd,$uid,$gid,
  2685.                           $quota,$comment,$gcos,$dir,$shell) = getpw...
  2686.                        ($name,$passwd,$gid,$members) = getgr...
  2687.                        ($name,$aliases,$addrtype,$length,@addrs) = gethost...
  2688.                        ($name,$aliases,$addrtype,$net) = getnet...
  2689.                        ($name,$aliases,$proto) = getproto...
  2690.                        ($name,$aliases,$port,$proto) = getserv...
  2691.  
  2692.                   (If the entry doesn't exist you get a null list.)
  2693.  
  2694.                   Within a scalar context, you get the name, unless
  2695.                   the function was a lookup by name, in which case you
  2696.                   get the other thing, whatever it is.  (If the entry
  2697.                   doesn't exist you get the undefined value.)  For
  2698.                   example:
  2699.  
  2700.  
  2701.  
  2702.  
  2703.      Page 41                                         (printed 1/17/94)
  2704.  
  2705.  
  2706.  
  2707.  
  2708.  
  2709.  
  2710.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2711.  
  2712.  
  2713.  
  2714.                        $uid = getpwnam
  2715.                        $name = getpwuid
  2716.                        $name = getpwent
  2717.                        $gid = getgrnam
  2718.                        $name = getgrgid
  2719.                        $name = getgrent
  2720.                        etc.
  2721.  
  2722.                   The $members value returned by getgr... is a space
  2723.                   separated list of the login names of the members of
  2724.                   the group.
  2725.  
  2726.                   For the gethost... functions, if the h_errno
  2727.                   variable is supported in C, it will be returned to
  2728.                   you via $? if the function call fails.  The @addrs
  2729.                   value returned by a successful call is a list of the
  2730.                   raw addresses returned by the corresponding system
  2731.                   library call.  In the Internet domain, each address
  2732.                   is four bytes long and you can unpack it by saying
  2733.                   something like:
  2734.  
  2735.                        ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  2736.  
  2737.  
  2738.           getsockname(SOCKET)
  2739.                   Returns the packed sockaddr address of this end of
  2740.                   the SOCKET connection.
  2741.  
  2742.                        # An internet sockaddr
  2743.                        $sockaddr = 'S n a4 x8';
  2744.                        $mysockaddr = getsockname(S);
  2745.                        ($family, $port, $myaddr) =
  2746.                                  unpack($sockaddr,$mysockaddr);
  2747.  
  2748.  
  2749.           getsockopt(SOCKET,LEVEL,OPTNAME)
  2750.                   Returns the socket option requested, or undefined if
  2751.                   there is an error.
  2752.  
  2753.           gmtime(EXPR)
  2754.  
  2755.           gmtime EXPR
  2756.                   Converts a time as returned by the time function to
  2757.                   a 9-element array with the time analyzed for the
  2758.                   Greenwich timezone.  Typically used as follows:
  2759.  
  2760.                   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2761.                                                 gmtime(time);
  2762.  
  2763.                   All array elements are numeric, and come straight
  2764.                   out of a struct tm.  In particular this means that
  2765.                   $mon has the range 0..11 and $wday has the range
  2766.  
  2767.  
  2768.  
  2769.      Page 42                                         (printed 1/17/94)
  2770.  
  2771.  
  2772.  
  2773.  
  2774.  
  2775.  
  2776.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2777.  
  2778.  
  2779.  
  2780.                   0..6.  If EXPR is omitted, does gmtime(time).
  2781.  
  2782.           goto LABEL
  2783.                   Finds the statement labeled with LABEL and resumes
  2784.                   execution there.  Currently you may only go to
  2785.                   statements in the main body of the program that are
  2786.                   not nested inside a do {} construct.  This statement
  2787.                   is not implemented very efficiently, and is here
  2788.                   only to make the sed-to-perl translator easier.  I
  2789.                   may change its semantics at any time, consistent
  2790.                   with support for translated sed scripts.  Use it at
  2791.                   your own risk.  Better yet, don't use it at all.
  2792.  
  2793.           grep(EXPR,LIST)
  2794.                   Evaluates EXPR for each element of LIST (locally
  2795.                   setting $_ to each element) and returns the array
  2796.                   value consisting of those elements for which the
  2797.                   expression evaluated to true.  In a scalar context,
  2798.                   returns the number of times the expression was true.
  2799.  
  2800.                        @foo = grep(!/^#/, @bar);    # weed out comments
  2801.  
  2802.                   Note that, since $_ is a reference into the array
  2803.                   value, it can be used to modify the elements of the
  2804.                   array.  While this is useful and supported, it can
  2805.                   cause bizarre results if the LIST is not a named
  2806.                   array.
  2807.  
  2808.           hex(EXPR)
  2809.  
  2810.           hex EXPR
  2811.                   Returns the decimal value of EXPR interpreted as an
  2812.                   hex string.  (To interpret strings that might start
  2813.                   with 0 or 0x see oct().)  If EXPR is omitted, uses
  2814.                   $_.
  2815.  
  2816.           index(STR,SUBSTR,POSITION)
  2817.  
  2818.           index(STR,SUBSTR)
  2819.                   Returns the position of the first occurrence of
  2820.                   SUBSTR in STR at or after POSITION.  If POSITION is
  2821.                   omitted, starts searching from the beginning of the
  2822.                   string.  The return value is based at 0, or whatever
  2823.                   you've set the $[ variable to.  If the substring is
  2824.                   not found, returns one less than the base,
  2825.                   ordinarily -1.
  2826.  
  2827.           int(EXPR)
  2828.  
  2829.           int EXPR
  2830.                   Returns the integer portion of EXPR.  If EXPR is
  2831.                   omitted, uses $_.
  2832.  
  2833.  
  2834.  
  2835.      Page 43                                         (printed 1/17/94)
  2836.  
  2837.  
  2838.  
  2839.  
  2840.  
  2841.  
  2842.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2843.  
  2844.  
  2845.  
  2846.           ioctl(FILEHANDLE,FUNCTION,SCALAR)
  2847.                   Implements the ioctl(2) function.  You'll probably
  2848.                   have to say
  2849.  
  2850.                        require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
  2851.  
  2852.                   first to get the correct function definitions.  If
  2853.                   ioctl.ph doesn't exist or doesn't have the correct
  2854.                   definitions you'll have to roll your own, based on
  2855.                   your C header files such as <sys/ioctl.h>.  (There
  2856.                   is a perl script called h2ph that comes with the
  2857.                   perl kit which may help you in this.)  SCALAR will
  2858.                   be read and/or written depending on the FUNCTION--a
  2859.                   pointer to the string value of SCALAR will be passed
  2860.                   as the third argument of the actual ioctl call.  (If
  2861.                   SCALAR has no string value but does have a numeric
  2862.                   value, that value will be passed rather than a
  2863.                   pointer to the string value.  To guarantee this to
  2864.                   be true, add a 0 to the scalar before using it.)
  2865.                   The pack() and unpack() functions are useful for
  2866.                   manipulating the values of structures used by
  2867.                   ioctl().  The following example sets the erase
  2868.                   character to DEL.
  2869.  
  2870.                        require 'ioctl.ph';
  2871.                        $sgttyb_t = "ccccs";          # 4 chars and a short
  2872.                        if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  2873.                             @ary = unpack($sgttyb_t,$sgttyb);
  2874.                             $ary[2] = 127;
  2875.                             $sgttyb = pack($sgttyb_t,@ary);
  2876.                             ioctl(STDIN,$TIOCSETP,$sgttyb)
  2877.                                  || die "Can't ioctl: $!";
  2878.                        }
  2879.  
  2880.                   The return value of ioctl (and fcntl) is as follows:
  2881.  
  2882.                        if OS returns:           perl returns:
  2883.                          -1                       undefined value
  2884.                          0                        string "0 but true"
  2885.                          anything else            that number
  2886.  
  2887.                   Thus perl returns true on success and false on
  2888.                   failure, yet you can still easily determine the
  2889.                   actual value returned by the operating system:
  2890.  
  2891.                        ($retval = ioctl(...)) || ($retval = -1);
  2892.                        printf "System returned %d\n", $retval;
  2893.  
  2894.  
  2895.  
  2896.  
  2897.  
  2898.  
  2899.  
  2900.  
  2901.      Page 44                                         (printed 1/17/94)
  2902.  
  2903.  
  2904.  
  2905.  
  2906.  
  2907.  
  2908.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2909.  
  2910.  
  2911.  
  2912.           join(EXPR,LIST)
  2913.  
  2914.           join(EXPR,ARRAY)
  2915.                   Joins the separate strings of LIST or ARRAY into a
  2916.                   single string with fields separated by the value of
  2917.                   EXPR, and returns the string.  Example:
  2918.  
  2919.                   $_ = join(':',
  2920.                             $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  2921.  
  2922.                   See split.
  2923.  
  2924.           keys(ASSOC_ARRAY)
  2925.  
  2926.           keys ASSOC_ARRAY
  2927.                   Returns a normal array consisting of all the keys of
  2928.                   the named associative array.  The keys are returned
  2929.                   in an apparently random order, but it is the same
  2930.                   order as either the values() or each() function
  2931.                   produces (given that the associative array has not
  2932.                   been modified).  Here is yet another way to print
  2933.                   your environment:
  2934.  
  2935.                        @keys = keys %ENV;
  2936.                        @values = values %ENV;
  2937.                        while ($#keys >= 0) {
  2938.                             print pop(@keys), '=', pop(@values), "\n";
  2939.                        }
  2940.  
  2941.                   or how about sorted by key:
  2942.  
  2943.                        foreach $key (sort(keys %ENV)) {
  2944.                             print $key, '=', $ENV{$key}, "\n";
  2945.                        }
  2946.  
  2947.  
  2948.           kill(LIST)
  2949.  
  2950.           kill LIST
  2951.                   Sends a signal to a list of processes.  The first
  2952.                   element of the list must be the signal to send.
  2953.                   Returns the number of processes successfully
  2954.                   signaled.
  2955.  
  2956.                        $cnt = kill 1, $child1, $child2;
  2957.                        kill 9, @goners;
  2958.  
  2959.                   If the signal is negative, kills process groups
  2960.                   instead of processes.  (On System V, a negative
  2961.                   process number will also kill process groups, but
  2962.                   that's not portable.)  You may use a signal name in
  2963.                   quotes.
  2964.  
  2965.  
  2966.  
  2967.      Page 45                                         (printed 1/17/94)
  2968.  
  2969.  
  2970.  
  2971.  
  2972.  
  2973.  
  2974.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  2975.  
  2976.  
  2977.  
  2978.           last LABEL
  2979.  
  2980.           last    The last command is like the break statement in C
  2981.                   (as used in loops); it immediately exits the loop in
  2982.                   question.  If the LABEL is omitted, the command
  2983.                   refers to the innermost enclosing loop.  The
  2984.                   continue block, if any, is not executed:
  2985.  
  2986.                        line: while (<STDIN>) {
  2987.                             last line if /^$/;  # exit when done with header
  2988.                             ...
  2989.                        }
  2990.  
  2991.  
  2992.           length(EXPR)
  2993.  
  2994.           length EXPR
  2995.                   Returns the length in characters of the value of
  2996.                   EXPR.  If EXPR is omitted, returns length of $_.
  2997.  
  2998.           link(OLDFILE,NEWFILE)
  2999.                   Creates a new filename linked to the old filename.
  3000.                   Returns 1 for success, 0 otherwise.
  3001.  
  3002.           listen(SOCKET,QUEUESIZE)
  3003.                   Does the same thing that the listen system call
  3004.                   does.  Returns true if it succeeded, false
  3005.                   otherwise.  See example in section on Interprocess
  3006.                   Communication.
  3007.  
  3008.           local(LIST)
  3009.                   Declares the listed variables to be local to the
  3010.                   enclosing block, subroutine, eval or "do".  All the
  3011.                   listed elements must be legal lvalues.  This
  3012.                   operator works by saving the current values of those
  3013.                   variables in LIST on a hidden stack and restoring
  3014.                   them upon exiting the block, subroutine or eval.
  3015.                   This means that called subroutines can also
  3016.                   reference the local variable, but not the global
  3017.                   one.  The LIST may be assigned to if desired, which
  3018.                   allows you to initialize your local variables.  (If
  3019.                   no initializer is given for a particular variable,
  3020.                   it is created with an undefined value.)  Commonly
  3021.                   this is used to name the parameters to a subroutine.
  3022.                   Examples:
  3023.  
  3024.  
  3025.  
  3026.  
  3027.  
  3028.  
  3029.  
  3030.  
  3031.  
  3032.  
  3033.      Page 46                                         (printed 1/17/94)
  3034.  
  3035.  
  3036.  
  3037.  
  3038.  
  3039.  
  3040.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3041.  
  3042.  
  3043.  
  3044.                        sub RANGEVAL {
  3045.                             local($min, $max, $thunk) = @_;
  3046.                             local($result) = '';
  3047.                             local($i);
  3048.  
  3049.                             # Presumably $thunk makes reference to $i
  3050.  
  3051.                             for ($i = $min; $i < $max; $i++) {
  3052.                                  $result .= eval $thunk;
  3053.                             }
  3054.  
  3055.                             $result;
  3056.                        }
  3057.  
  3058.                        if ($sw eq '-v') {
  3059.                            # init local array with global array
  3060.                            local(@ARGV) = @ARGV;
  3061.                            unshift(@ARGV,'echo');
  3062.                            system @ARGV;
  3063.                        }
  3064.                        # @ARGV restored
  3065.  
  3066.                        # temporarily add to digits associative array
  3067.                        if ($base12) {
  3068.                             # (NOTE: not claiming this is efficient!)
  3069.                             local(%digits) = (%digits,'t',10,'e',11);
  3070.                             do parse_num();
  3071.                        }
  3072.  
  3073.                   Note that local() is a run-time command, and so gets
  3074.                   executed every time through a loop, using up more
  3075.                   stack storage each time until it's all released at
  3076.                   once when the loop is exited.
  3077.  
  3078.           localtime(EXPR)
  3079.  
  3080.           localtime EXPR
  3081.                   Converts a time as returned by the time function to
  3082.                   a 9-element array with the time analyzed for the
  3083.                   local timezone.  Typically used as follows:
  3084.  
  3085.                   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  3086.                                                 localtime(time);
  3087.  
  3088.                   All array elements are numeric, and come straight
  3089.                   out of a struct tm.  In particular this means that
  3090.                   $mon has the range 0..11 and $wday has the range
  3091.                   0..6.  If EXPR is omitted, does localtime(time).
  3092.  
  3093.           log(EXPR)
  3094.  
  3095.  
  3096.  
  3097.  
  3098.  
  3099.      Page 47                                         (printed 1/17/94)
  3100.  
  3101.  
  3102.  
  3103.  
  3104.  
  3105.  
  3106.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3107.  
  3108.  
  3109.  
  3110.           log EXPR
  3111.                   Returns logarithm (base e) of EXPR.  If EXPR is
  3112.                   omitted, returns log of $_.
  3113.  
  3114.           lstat(FILEHANDLE)
  3115.  
  3116.           lstat FILEHANDLE
  3117.  
  3118.           lstat(EXPR)
  3119.  
  3120.           lstat SCALARVARIABLE
  3121.                   Does the same thing as the stat() function, but
  3122.                   stats a symbolic link instead of the file the
  3123.                   symbolic link points to.  If symbolic links are
  3124.                   unimplemented on your system, a normal stat is done.
  3125.  
  3126.           m/PATTERN/gio
  3127.  
  3128.           /PATTERN/gio
  3129.                   Searches a string for a pattern match, and returns
  3130.                   true (1) or false ('').  If no string is specified
  3131.                   via the =~ or !~ operator, the $_ string is
  3132.                   searched.  (The string specified with =~ need not be
  3133.                   an lvalue--it may be the result of an expression
  3134.                   evaluation, but remember the =~ binds rather
  3135.                   tightly.)  See also the section on regular
  3136.                   expressions.
  3137.  
  3138.                   If / is the delimiter then the initial 'm' is
  3139.                   optional.  With the 'm' you can use any pair of
  3140.                   non-alphanumeric characters as delimiters.  This is
  3141.                   particularly useful for matching Unix path names
  3142.                   that contain '/'.  If the final delimiter is
  3143.                   followed by the optional letter 'i', the matching is
  3144.                   done in a case-insensitive manner.  PATTERN may
  3145.                   contain references to scalar variables, which will
  3146.                   be interpolated (and the pattern recompiled) every
  3147.                   time the pattern search is evaluated.  (Note that $)
  3148.                   and $| may not be interpolated because they look
  3149.                   like end-of-string tests.)  If you want such a
  3150.                   pattern to be compiled only once, add an "o" after
  3151.                   the trailing delimiter.  This avoids expensive run-
  3152.                   time recompilations, and is useful when the value
  3153.                   you are interpolating won't change over the life of
  3154.                   the script.  If the PATTERN evaluates to a null
  3155.                   string, the most recent successful regular
  3156.                   expression is used instead.
  3157.  
  3158.                   If used in a context that requires an array value, a
  3159.                   pattern match returns an array consisting of the
  3160.                   subexpressions matched by the parentheses in the
  3161.                   pattern, i.e. ($1, $2, $3...).  It does NOT actually
  3162.  
  3163.  
  3164.  
  3165.      Page 48                                         (printed 1/17/94)
  3166.  
  3167.  
  3168.  
  3169.  
  3170.  
  3171.  
  3172.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3173.  
  3174.  
  3175.  
  3176.                   set $1, $2, etc. in this case, nor does it set $+,
  3177.                   $`, $& or $'.  If the match fails, a null array is
  3178.                   returned.  If the match succeeds, but there were no
  3179.                   parentheses, an array value of (1) is returned.
  3180.  
  3181.                   Examples:
  3182.  
  3183.                       open(tty, '/dev/tty');
  3184.                       <tty> =~ /^y/i && do foo();    # do foo if desired
  3185.  
  3186.                       if (/Version: *([0-9.]*)/) { $version = $1; }
  3187.  
  3188.                       next if m#^/usr/spool/uucp#;
  3189.  
  3190.                       # poor man's grep
  3191.                       $arg = shift;
  3192.                       while (<>) {
  3193.                            print if /$arg/o;    # compile only once
  3194.                       }
  3195.  
  3196.                       if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  3197.  
  3198.                   This last example splits $foo into the first two
  3199.                   words and the remainder of the line, and assigns
  3200.                   those three fields to $F1, $F2 and $Etc.  The
  3201.                   conditional is true if any variables were assigned,
  3202.                   i.e. if the pattern matched.
  3203.  
  3204.                   The "g" modifier specifies global pattern
  3205.                   matching--that is, matching as many times as
  3206.                   possible within the string.  How it behaves depends
  3207.                   on the context.  In an array context, it returns a
  3208.                   list of all the substrings matched by all the
  3209.                   parentheses in the regular expression.  If there are
  3210.                   no parentheses, it returns a list of all the matched
  3211.                   strings, as if there were parentheses around the
  3212.                   whole pattern.  In a scalar context, it iterates
  3213.                   through the string, returning TRUE each time it
  3214.                   matches, and FALSE when it eventually runs out of
  3215.                   matches.  (In other words, it remembers where it
  3216.                   left off last time and restarts the search at that
  3217.                   point.)  It presumes that you have not modified the
  3218.                   string since the last match.  Modifying the string
  3219.                   between matches may result in undefined behavior.
  3220.                   (You can actually get away with in-place
  3221.                   modifications via substr() that do not change the
  3222.                   length of the entire string.  In general, however,
  3223.                   you should be using s///g for such modifications.)
  3224.                   Examples:
  3225.  
  3226.                        # array context
  3227.                        ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  3228.  
  3229.  
  3230.  
  3231.      Page 49                                         (printed 1/17/94)
  3232.  
  3233.  
  3234.  
  3235.  
  3236.  
  3237.  
  3238.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3239.  
  3240.  
  3241.  
  3242.                        # scalar context
  3243.                        $/ = ""; $* = 1;
  3244.                        while ($paragraph = <>) {
  3245.                            while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  3246.                             $sentences++;
  3247.                            }
  3248.                        }
  3249.                        print "$sentences\n";
  3250.  
  3251.  
  3252.           mkdir(FILENAME,MODE)
  3253.                   Creates the directory specified by FILENAME, with
  3254.                   permissions specified by MODE (as modified by
  3255.                   umask).  If it succeeds it returns 1, otherwise it
  3256.                   returns 0 and sets $! (errno).
  3257.  
  3258.           msgctl(ID,CMD,ARG)
  3259.                   Calls the System V IPC function msgctl.  If CMD is
  3260.                   &IPC_STAT, then ARG must be a variable which will
  3261.                   hold the returned msqid_ds structure.  Returns like
  3262.                   ioctl: the undefined value for error, "0 but true"
  3263.                   for zero, or the actual return value otherwise.
  3264.  
  3265.           msgget(KEY,FLAGS)
  3266.                   Calls the System V IPC function msgget.  Returns the
  3267.                   message queue id, or the undefined value if there is
  3268.                   an error.
  3269.  
  3270.           msgsnd(ID,MSG,FLAGS)
  3271.                   Calls the System V IPC function msgsnd to send the
  3272.                   message MSG to the message queue ID.  MSG must begin
  3273.                   with the long integer message type, which may be
  3274.                   created with pack("L", $type).  Returns true if
  3275.                   successful, or false if there is an error.
  3276.  
  3277.           msgrcv(ID,VAR,SIZE,TYPE,FLAGS)
  3278.                   Calls the System V IPC function msgrcv to receive a
  3279.                   message from message queue ID into variable VAR with
  3280.                   a maximum message size of SIZE.  Note that if a
  3281.                   message is received, the message type will be the
  3282.                   first thing in VAR, and the maximum length of VAR is
  3283.                   SIZE plus the size of the message type.  Returns
  3284.                   true if successful, or false if there is an error.
  3285.  
  3286.           next LABEL
  3287.  
  3288.           next    The next command is like the continue statement in
  3289.                   C; it starts the next iteration of the loop:
  3290.  
  3291.  
  3292.  
  3293.  
  3294.  
  3295.  
  3296.  
  3297.      Page 50                                         (printed 1/17/94)
  3298.  
  3299.  
  3300.  
  3301.  
  3302.  
  3303.  
  3304.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3305.  
  3306.  
  3307.  
  3308.                        line: while (<STDIN>) {
  3309.                             next line if /^#/;  # discard comments
  3310.                             ...
  3311.                        }
  3312.  
  3313.                   Note that if there were a continue block on the
  3314.                   above, it would get executed even on discarded
  3315.                   lines.  If the LABEL is omitted, the command refers
  3316.                   to the innermost enclosing loop.
  3317.  
  3318.           oct(EXPR)
  3319.  
  3320.           oct EXPR
  3321.                   Returns the decimal value of EXPR interpreted as an
  3322.                   octal string.  (If EXPR happens to start off with
  3323.                   0x, interprets it as a hex string instead.)  The
  3324.                   following will handle decimal, octal and hex in the
  3325.                   standard notation:
  3326.  
  3327.                        $val = oct($val) if $val =~ /^0/;
  3328.  
  3329.                   If EXPR is omitted, uses $_.
  3330.  
  3331.           open(FILEHANDLE,EXPR)
  3332.  
  3333.           open(FILEHANDLE)
  3334.  
  3335.           open FILEHANDLE
  3336.                   Opens the file whose filename is given by EXPR, and
  3337.                   associates it with FILEHANDLE.  If FILEHANDLE is an
  3338.                   expression, its value is used as the name of the
  3339.                   real filehandle wanted.  If EXPR is omitted, the
  3340.                   scalar variable of the same name as the FILEHANDLE
  3341.                   contains the filename.  If the filename begins with
  3342.                   "<" or nothing, the file is opened for input.  If
  3343.                   the filename begins with ">", the file is opened for
  3344.                   output.  If the filename begins with ">>", the file
  3345.                   is opened for appending.  (You can put a '+' in
  3346.                   front of the '>' or '<' to indicate that you want
  3347.                   both read and write access to the file.)  If the
  3348.                   filename begins with "|", the filename is
  3349.                   interpreted as a command to which output is to be
  3350.                   piped, and if the filename ends with a "|", the
  3351.                   filename is interpreted as command which pipes input
  3352.                   to us.  (You may not have a command that pipes both
  3353.                   in and out.)  Opening '-' opens STDIN and opening
  3354.                   '>-' opens STDOUT.  Open returns non-zero upon
  3355.                   success, the undefined value otherwise.  If the open
  3356.                   involved a pipe, the return value happens to be the
  3357.                   pid of the subprocess.  Examples:
  3358.  
  3359.  
  3360.  
  3361.  
  3362.  
  3363.      Page 51                                         (printed 1/17/94)
  3364.  
  3365.  
  3366.  
  3367.  
  3368.  
  3369.  
  3370.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3371.  
  3372.  
  3373.  
  3374.                        $article = 100;
  3375.                        open article || die "Can't find article $article: $!\n";
  3376.                        while (<article>) {...
  3377.  
  3378.                        open(LOG, '>>/usr/spool/news/twitlog');
  3379.                                            # (log is reserved)
  3380.  
  3381.                        open(article, "caesar <$article |");
  3382.                                            # decrypt article
  3383.  
  3384.                        open(extract, "|sort >/tmp/Tmp$$");
  3385.                                            # $$ is our process#
  3386.  
  3387.                        # process argument list of files along with any includes
  3388.  
  3389.                        foreach $file (@ARGV) {
  3390.                             do process($file, 'fh00');    # no pun intended
  3391.                        }
  3392.  
  3393.                        sub process {
  3394.                             local($filename, $input) = @_;
  3395.                             $input++;      # this is a string increment
  3396.                             unless (open($input, $filename)) {
  3397.                                  print STDERR "Can't open $filename: $!\n";
  3398.                                  return;
  3399.                             }
  3400.                             while (<$input>) {       # note use of indirection
  3401.                                  if (/^#include "(.*)"/) {
  3402.                                       do process($1, $input);
  3403.                                       next;
  3404.                                  }
  3405.                                  ...       # whatever
  3406.                             }
  3407.                        }
  3408.  
  3409.                   You may also, in the Bourne shell tradition, specify
  3410.                   an EXPR beginning with ">&", in which case the rest
  3411.                   of the string is interpreted as the name of a
  3412.                   filehandle (or file descriptor, if numeric) which is
  3413.                   to be duped and opened.  You may use & after >, >>,
  3414.                   <, +>, +>> and +<.  The mode you specify should
  3415.                   match the mode of the original filehandle.  Here is
  3416.                   a script that saves, redirects, and restores STDOUT
  3417.                   and STDERR:
  3418.  
  3419.  
  3420.  
  3421.  
  3422.  
  3423.  
  3424.  
  3425.  
  3426.  
  3427.  
  3428.  
  3429.      Page 52                                         (printed 1/17/94)
  3430.  
  3431.  
  3432.  
  3433.  
  3434.  
  3435.  
  3436.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3437.  
  3438.  
  3439.  
  3440.                        #!/usr/bin/perl
  3441.                        open(SAVEOUT, ">&STDOUT");
  3442.                        open(SAVEERR, ">&STDERR");
  3443.  
  3444.                        open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  3445.                        open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  3446.  
  3447.                        select(STDERR); $| = 1;       # make unbuffered
  3448.                        select(STDOUT); $| = 1;       # make unbuffered
  3449.  
  3450.                        print STDOUT "stdout 1\n";    # this works for
  3451.                        print STDERR "stderr 1\n";    # subprocesses too
  3452.  
  3453.                        close(STDOUT);
  3454.                        close(STDERR);
  3455.  
  3456.                        open(STDOUT, ">&SAVEOUT");
  3457.                        open(STDERR, ">&SAVEERR");
  3458.  
  3459.                        print STDOUT "stdout 2\n";
  3460.                        print STDERR "stderr 2\n";
  3461.  
  3462.                   If you open a pipe on the command "-", i.e. either
  3463.                   "|-" or "-|", then there is an implicit fork done,
  3464.                   and the return value of open is the pid of the child
  3465.                   within the parent process, and 0 within the child
  3466.                   process.  (Use defined($pid) to determine if the
  3467.                   open was successful.)  The filehandle behaves
  3468.                   normally for the parent, but i/o to that filehandle
  3469.                   is piped from/to the STDOUT/STDIN of the child
  3470.                   process.  In the child process the filehandle isn't
  3471.                   opened--i/o happens from/to the new STDOUT or STDIN.
  3472.                   Typically this is used like the normal piped open
  3473.                   when you want to exercise more control over just how
  3474.                   the pipe command gets executed, such as when you are
  3475.                   running setuid, and don't want to have to scan shell
  3476.                   commands for metacharacters.  The following pairs
  3477.                   are more or less equivalent:
  3478.  
  3479.                        open(FOO, "|tr '[a-z]' '[A-Z]'");
  3480.                        open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  3481.  
  3482.                        open(FOO, "cat -n '$file'|");
  3483.                        open(FOO, "-|") || exec 'cat', '-n', $file;
  3484.  
  3485.                   Explicitly closing any piped filehandle causes the
  3486.                   parent process to wait for the child to finish, and
  3487.                   returns the status value in $?.  Note: on any
  3488.                   operation which may do a fork, unflushed buffers
  3489.                   remain unflushed in both processes, which means you
  3490.                   may need to set $| to avoid duplicate output.
  3491.  
  3492.  
  3493.  
  3494.  
  3495.      Page 53                                         (printed 1/17/94)
  3496.  
  3497.  
  3498.  
  3499.  
  3500.  
  3501.  
  3502.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3503.  
  3504.  
  3505.  
  3506.                   The filename that is passed to open will have
  3507.                   leading and trailing whitespace deleted.  In order
  3508.                   to open a file with arbitrary weird characters in
  3509.                   it, it's necessary to protect any leading and
  3510.                   trailing whitespace thusly:
  3511.  
  3512.                           $file =~ s#^(\s)#./$1#;
  3513.                           open(FOO, "< $file\0");
  3514.  
  3515.  
  3516.           opendir(DIRHANDLE,EXPR)
  3517.                   Opens a directory named EXPR for processing by
  3518.                   readdir(), telldir(), seekdir(), rewinddir() and
  3519.                   closedir().  Returns true if successful.  DIRHANDLEs
  3520.                   have their own namespace separate from FILEHANDLEs.
  3521.  
  3522.           ord(EXPR)
  3523.  
  3524.           ord EXPR
  3525.                   Returns the numeric ascii value of the first
  3526.                   character of EXPR.  If EXPR is omitted, uses $_.
  3527.  
  3528.           pack(TEMPLATE,LIST)
  3529.                   Takes an array or list of values and packs it into a
  3530.                   binary structure, returning the string containing
  3531.                   the structure.  The TEMPLATE is a sequence of
  3532.                   characters that give the order and type of values,
  3533.                   as follows:
  3534.  
  3535.                        A    An ascii string, will be space padded.
  3536.                        a    An ascii string, will be null padded.
  3537.                        c    A signed char value.
  3538.                        C    An unsigned char value.
  3539.                        s    A signed short value.
  3540.                        S    An unsigned short value.
  3541.                        i    A signed integer value.
  3542.                        I    An unsigned integer value.
  3543.                        l    A signed long value.
  3544.                        L    An unsigned long value.
  3545.                        n    A short in "network" order.
  3546.                        N    A long in "network" order.
  3547.                        f    A single-precision float in the native format.
  3548.                        d    A double-precision float in the native format.
  3549.                        p    A pointer to a string.
  3550.                        v    A short in "VAX" (little-endian) order.
  3551.                        V    A long in "VAX" (little-endian) order.
  3552.                        x    A null byte.
  3553.                        X    Back up a byte.
  3554.                        @    Null fill to absolute position.
  3555.                        u    A uuencoded string.
  3556.                        b    A bit string (ascending bit order, like vec()).
  3557.                        B    A bit string (descending bit order).
  3558.  
  3559.  
  3560.  
  3561.      Page 54                                         (printed 1/17/94)
  3562.  
  3563.  
  3564.  
  3565.  
  3566.  
  3567.  
  3568.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3569.  
  3570.  
  3571.  
  3572.                        h    A hex string (low nybble first).
  3573.                        H    A hex string (high nybble first).
  3574.  
  3575.                   Each letter may optionally be followed by a number
  3576.                   which gives a repeat count.  With all types except
  3577.                   "a", "A", "b", "B", "h" and "H", the pack function
  3578.                   will gobble up that many values from the LIST.  A *
  3579.                   for the repeat count means to use however many items
  3580.                   are left.  The "a" and "A" types gobble just one
  3581.                   value, but pack it as a string of length count,
  3582.                   padding with nulls or spaces as necessary.  (When
  3583.                   unpacking, "A" strips trailing spaces and nulls, but
  3584.                   "a" does not.)  Likewise, the "b" and "B" fields
  3585.                   pack a string that many bits long.  The "h" and "H"
  3586.                   fields pack a string that many nybbles long.  Real
  3587.                   numbers (floats and doubles) are in the native
  3588.                   machine format only; due to the multiplicity of
  3589.                   floating formats around, and the lack of a standard
  3590.                   "network" representation, no facility for
  3591.                   interchange has been made.  This means that packed
  3592.                   floating point data written on one machine may not
  3593.                   be readable on another - even if both use IEEE
  3594.                   floating point arithmetic (as the endian-ness of the
  3595.                   memory representation is not part of the IEEE spec).
  3596.                   Note that perl uses doubles internally for all
  3597.                   numeric calculation, and converting from double ->
  3598.                   float -> double will lose precision (i.e.
  3599.                   unpack("f", pack("f", $foo)) will not in general
  3600.                   equal $foo).
  3601.                   Examples:
  3602.  
  3603.                        $foo = pack("cccc",65,66,67,68);
  3604.                        # foo eq "ABCD"
  3605.                        $foo = pack("c4",65,66,67,68);
  3606.                        # same thing
  3607.  
  3608.                        $foo = pack("ccxxcc",65,66,67,68);
  3609.                        # foo eq "AB\0\0CD"
  3610.  
  3611.                        $foo = pack("s2",1,2);
  3612.                        # "\1\0\2\0" on little-endian
  3613.                        # "\0\1\0\2" on big-endian
  3614.  
  3615.                        $foo = pack("a4","abcd","x","y","z");
  3616.                        # "abcd"
  3617.  
  3618.                        $foo = pack("aaaa","abcd","x","y","z");
  3619.                        # "axyz"
  3620.  
  3621.                        $foo = pack("a14","abcdefg");
  3622.                        # "abcdefg\0\0\0\0\0\0\0"
  3623.  
  3624.  
  3625.  
  3626.  
  3627.      Page 55                                         (printed 1/17/94)
  3628.  
  3629.  
  3630.  
  3631.  
  3632.  
  3633.  
  3634.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3635.  
  3636.  
  3637.  
  3638.                        $foo = pack("i9pl", gmtime);
  3639.                        # a real struct tm (on my system anyway)
  3640.  
  3641.                        sub bintodec {
  3642.                            unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  3643.                        }
  3644.                   The same template may generally also be used in the
  3645.                   unpack function.
  3646.  
  3647.           pipe(READHANDLE,WRITEHANDLE)
  3648.                   Opens a pair of connected pipes like the
  3649.                   corresponding system call.  Note that if you set up
  3650.                   a loop of piped processes, deadlock can occur unless
  3651.                   you are very careful.  In addition, note that perl's
  3652.                   pipes use stdio buffering, so you may need to set $|
  3653.                   to flush your WRITEHANDLE after each command,
  3654.                   depending on the application.  [Requires version 3.0
  3655.                   patchlevel 9.]
  3656.  
  3657.           pop(ARRAY)
  3658.  
  3659.           pop ARRAY
  3660.                   Pops and returns the last value of the array,
  3661.                   shortening the array by 1.  Has the same effect as
  3662.  
  3663.                        $tmp = $ARRAY[$#ARRAY--];
  3664.  
  3665.                   If there are no elements in the array, returns the
  3666.                   undefined value.
  3667.  
  3668.           print(FILEHANDLE LIST)
  3669.  
  3670.           print(LIST)
  3671.  
  3672.           print FILEHANDLE LIST
  3673.  
  3674.           print LIST
  3675.  
  3676.           print   Prints a string or a comma-separated list of
  3677.                   strings.  Returns non-zero if successful.
  3678.                   FILEHANDLE may be a scalar variable name, in which
  3679.                   case the variable contains the name of the
  3680.                   filehandle, thus introducing one level of
  3681.                   indirection.  (NOTE: If FILEHANDLE is a variable and
  3682.                   the next token is a term, it may be misinterpreted
  3683.                   as an operator unless you interpose a + or put
  3684.                   parens around the arguments.)  If FILEHANDLE is
  3685.                   omitted, prints by default to standard output (or to
  3686.                   the last selected output channel--see select()).  If
  3687.                   LIST is also omitted, prints $_ to STDOUT.  To set
  3688.                   the default output channel to something other than
  3689.                   STDOUT use the select operation.  Note that, because
  3690.  
  3691.  
  3692.  
  3693.      Page 56                                         (printed 1/17/94)
  3694.  
  3695.  
  3696.  
  3697.  
  3698.  
  3699.  
  3700.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3701.  
  3702.  
  3703.  
  3704.                   print takes a LIST, anything in the LIST is
  3705.                   evaluated in an array context, and any subroutine
  3706.                   that you call will have one or more of its
  3707.                   expressions evaluated in an array context.  Also be
  3708.                   careful not to follow the print keyword with a left
  3709.                   parenthesis unless you want the corresponding right
  3710.                   parenthesis to terminate the arguments to the
  3711.                   print--interpose a + or put parens around all the
  3712.                   arguments.
  3713.  
  3714.           printf(FILEHANDLE LIST)
  3715.  
  3716.           printf(LIST)
  3717.  
  3718.           printf FILEHANDLE LIST
  3719.  
  3720.           printf LIST
  3721.                   Equivalent to a "print FILEHANDLE sprintf(LIST)".
  3722.  
  3723.           push(ARRAY,LIST)
  3724.                   Treats ARRAY (@ is optional) as a stack, and pushes
  3725.                   the values of LIST onto the end of ARRAY.  The
  3726.                   length of ARRAY increases by the length of LIST.
  3727.                   Has the same effect as
  3728.  
  3729.                       for $value (LIST) {
  3730.                            $ARRAY[++$#ARRAY] = $value;
  3731.                       }
  3732.  
  3733.                   but is more efficient.
  3734.  
  3735.           q/STRING/
  3736.  
  3737.           qq/STRING/
  3738.  
  3739.           qx/STRING/
  3740.                   These are not really functions, but simply syntactic
  3741.                   sugar to let you avoid putting too many backslashes
  3742.                   into quoted strings.  The q operator is a
  3743.                   generalized single quote, and the qq operator a
  3744.                   generalized double quote.  The qx operator is a
  3745.                   generalized backquote.  Any non-alphanumeric
  3746.                   delimiter can be used in place of /, including
  3747.                   newline.  If the delimiter is an opening bracket or
  3748.                   parenthesis, the final delimiter will be the
  3749.                   corresponding closing bracket or parenthesis.
  3750.                   (Embedded occurrences of the closing bracket need to
  3751.                   be backslashed as usual.)  Examples:
  3752.  
  3753.  
  3754.  
  3755.  
  3756.  
  3757.  
  3758.  
  3759.      Page 57                                         (printed 1/17/94)
  3760.  
  3761.  
  3762.  
  3763.  
  3764.  
  3765.  
  3766.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3767.  
  3768.  
  3769.  
  3770.                        $foo = q!I said, "You said, 'She said it.'"!;
  3771.                        $bar = q('This is it.');
  3772.                        $today = qx{ date };
  3773.                        $_ .= qq
  3774.                   *** The previous line contains the naughty word "$&".\n
  3775.                             if /(ibm|apple|awk)/;      # :-)
  3776.  
  3777.  
  3778.           rand(EXPR)
  3779.  
  3780.           rand EXPR
  3781.  
  3782.           rand    Returns a random fractional number between 0 and the
  3783.                   value of EXPR.  (EXPR should be positive.)  If EXPR
  3784.                   is omitted, returns a value between 0 and 1.  See
  3785.                   also srand().
  3786.  
  3787.           read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3788.  
  3789.           read(FILEHANDLE,SCALAR,LENGTH)
  3790.                   Attempts to read LENGTH bytes of data into variable
  3791.                   SCALAR from the specified FILEHANDLE.  Returns the
  3792.                   number of bytes actually read, or undef if there was
  3793.                   an error.  SCALAR will be grown or shrunk to the
  3794.                   length actually read.  An OFFSET may be specified to
  3795.                   place the read data at some other place than the
  3796.                   beginning of the string.  This call is actually
  3797.                   implemented in terms of stdio's fread call.  To get
  3798.                   a true read system call, see sysread.
  3799.  
  3800.           readdir(DIRHANDLE)
  3801.  
  3802.           readdir DIRHANDLE
  3803.                   Returns the next directory entry for a directory
  3804.                   opened by opendir().  If used in an array context,
  3805.                   returns all the rest of the entries in the
  3806.                   directory.  If there are no more entries, returns an
  3807.                   undefined value in a scalar context or a null list
  3808.                   in an array context.
  3809.  
  3810.           readlink(EXPR)
  3811.  
  3812.           readlink EXPR
  3813.                   Returns the value of a symbolic link, if symbolic
  3814.                   links are implemented.  If not, gives a fatal error.
  3815.                   If there is some system error, returns the undefined
  3816.                   value and sets $! (errno).  If EXPR is omitted, uses
  3817.                   $_.
  3818.  
  3819.           recv(SOCKET,SCALAR,LEN,FLAGS)
  3820.                   Receives a message on a socket.  Attempts to receive
  3821.                   LENGTH bytes of data into variable SCALAR from the
  3822.  
  3823.  
  3824.  
  3825.      Page 58                                         (printed 1/17/94)
  3826.  
  3827.  
  3828.  
  3829.  
  3830.  
  3831.  
  3832.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3833.  
  3834.  
  3835.  
  3836.                   specified SOCKET filehandle.  Returns the address of
  3837.                   the sender, or the undefined value if there's an
  3838.                   error.  SCALAR will be grown or shrunk to the length
  3839.                   actually read.  Takes the same flags as the system
  3840.                   call of the same name.
  3841.  
  3842.           redo LABEL
  3843.  
  3844.           redo    The redo command restarts the loop block without
  3845.                   evaluating the conditional again.  The continue
  3846.                   block, if any, is not executed.  If the LABEL is
  3847.                   omitted, the command refers to the innermost
  3848.                   enclosing loop.  This command is normally used by
  3849.                   programs that want to lie to themselves about what
  3850.                   was just input:
  3851.  
  3852.                        # a simpleminded Pascal comment stripper
  3853.                        # (warning: assumes no { or } in strings)
  3854.                        line: while (<STDIN>) {
  3855.                             while (s|({.*}.*){.*}|$1 |) {}
  3856.                             s|{.*}| |;
  3857.                             if (s|{.*| |) {
  3858.                                  $front = $_;
  3859.                                  while (<STDIN>) {
  3860.                                       if (/}/) {     # end of comment?
  3861.                                            s|^|$front{|;
  3862.                                            redo line;
  3863.                                       }
  3864.                                  }
  3865.                             }
  3866.                             print;
  3867.                        }
  3868.  
  3869.  
  3870.           rename(OLDNAME,NEWNAME)
  3871.                   Changes the name of a file.  Returns 1 for success,
  3872.                   0 otherwise.  Will not work across filesystem
  3873.                   boundaries.
  3874.  
  3875.           require(EXPR)
  3876.  
  3877.           require EXPR
  3878.  
  3879.           require Includes the library file specified by EXPR, or by
  3880.                   $_ if EXPR is not supplied.  Has semantics similar
  3881.                   to the following subroutine:
  3882.  
  3883.                        sub require {
  3884.                            local($filename) = @_;
  3885.                            return 1 if $INC{$filename};
  3886.                            local($realfilename,$result);
  3887.                            ITER: {
  3888.  
  3889.  
  3890.  
  3891.      Page 59                                         (printed 1/17/94)
  3892.  
  3893.  
  3894.  
  3895.  
  3896.  
  3897.  
  3898.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3899.  
  3900.  
  3901.  
  3902.                             foreach $prefix (@INC) {
  3903.                                 $realfilename = "$prefix/$filename";
  3904.                                 if (-f $realfilename) {
  3905.                                  $result = do $realfilename;
  3906.                                  last ITER;
  3907.                                 }
  3908.                             }
  3909.                             die "Can't find $filename in \@INC";
  3910.                            }
  3911.                            die $@ if $@;
  3912.                            die "$filename did not return true value" unless $result;
  3913.                            $INC{$filename} = $realfilename;
  3914.                            $result;
  3915.                        }
  3916.  
  3917.                   Note that the file will not be included twice under
  3918.                   the same specified name.  The file must return true
  3919.                   as the last statement to indicate successful
  3920.                   execution of any initialization code, so it's
  3921.                   customary to end such a file with "1;" unless you're
  3922.                   sure it'll return true otherwise.
  3923.  
  3924.           reset(EXPR)
  3925.  
  3926.           reset EXPR
  3927.  
  3928.           reset   Generally used in a continue block at the end of a
  3929.                   loop to clear variables and reset ?? searches so
  3930.                   that they work again.  The expression is interpreted
  3931.                   as a list of single characters (hyphens allowed for
  3932.                   ranges).  All variables and arrays beginning with
  3933.                   one of those letters are reset to their pristine
  3934.                   state.  If the expression is omitted, one-match
  3935.                   searches (?pattern?) are reset to match again.  Only
  3936.                   resets variables or searches in the current package.
  3937.                   Always returns 1.  Examples:
  3938.  
  3939.                       reset 'X';      # reset all X variables
  3940.                       reset 'a-z';    # reset lower case variables
  3941.                       reset;          # just reset ?? searches
  3942.  
  3943.                   Note: resetting "A-Z" is not recommended since
  3944.                   you'll wipe out your ARGV and ENV arrays.
  3945.  
  3946.                   The use of reset on dbm associative arrays does not
  3947.                   change the dbm file.  (It does, however, flush any
  3948.                   entries cached by perl, which may be useful if you
  3949.                   are sharing the dbm file.  Then again, maybe not.)
  3950.  
  3951.           return LIST
  3952.                   Returns from a subroutine with the value specified.
  3953.                   (Note that a subroutine can automatically return the
  3954.  
  3955.  
  3956.  
  3957.      Page 60                                         (printed 1/17/94)
  3958.  
  3959.  
  3960.  
  3961.  
  3962.  
  3963.  
  3964.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  3965.  
  3966.  
  3967.  
  3968.                   value of the last expression evaluated.  That's the
  3969.                   preferred method--use of an explicit return is a bit
  3970.                   slower.)
  3971.  
  3972.           reverse(LIST)
  3973.  
  3974.           reverse LIST
  3975.                   In an array context, returns an array value
  3976.                   consisting of the elements of LIST in the opposite
  3977.                   order.  In a scalar context, returns a string value
  3978.                   consisting of the bytes of the first element of LIST
  3979.                   in the opposite order.
  3980.  
  3981.           rewinddir(DIRHANDLE)
  3982.  
  3983.           rewinddir DIRHANDLE
  3984.                   Sets the current position to the beginning of the
  3985.                   directory for the readdir() routine on DIRHANDLE.
  3986.  
  3987.           rindex(STR,SUBSTR,POSITION)
  3988.  
  3989.           rindex(STR,SUBSTR)
  3990.                   Works just like index except that it returns the
  3991.                   position of the LAST occurrence of SUBSTR in STR.
  3992.                   If POSITION is specified, returns the last
  3993.                   occurrence at or before that position.
  3994.  
  3995.           rmdir(FILENAME)
  3996.  
  3997.           rmdir FILENAME
  3998.                   Deletes the directory specified by FILENAME if it is
  3999.                   empty.  If it succeeds it returns 1, otherwise it
  4000.                   returns 0 and sets $! (errno).  If FILENAME is
  4001.                   omitted, uses $_.
  4002.  
  4003.           s/PATTERN/REPLACEMENT/gieo
  4004.                   Searches a string for a pattern, and if found,
  4005.                   replaces that pattern with the replacement text and
  4006.                   returns the number of substitutions made.  Otherwise
  4007.                   it returns false (0).  The "g" is optional, and if
  4008.                   present, indicates that all occurrences of the
  4009.                   pattern are to be replaced.  The "i" is also
  4010.                   optional, and if present, indicates that matching is
  4011.                   to be done in a case-insensitive manner.  The "e" is
  4012.                   likewise optional, and if present, indicates that
  4013.                   the replacement string is to be evaluated as an
  4014.                   expression rather than just as a double-quoted
  4015.                   string.  Any non-alphanumeric delimiter may replace
  4016.                   the slashes; if single quotes are used, no
  4017.                   interpretation is done on the replacement string
  4018.                   (the e modifier overrides this, however); if
  4019.                   backquotes are used, the replacement string is a
  4020.  
  4021.  
  4022.  
  4023.      Page 61                                         (printed 1/17/94)
  4024.  
  4025.  
  4026.  
  4027.  
  4028.  
  4029.  
  4030.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4031.  
  4032.  
  4033.  
  4034.                   command to execute whose output will be used as the
  4035.                   actual replacement text.  If the PATTERN is
  4036.                   delimited by bracketing quotes, the REPLACEMENT has
  4037.                   its own pair of quotes, which may or may not be
  4038.                   bracketing quotes, e.g.  s(foo)(bar) or s<foo>/bar/.
  4039.                   If no string is specified via the =~ or !~ operator,
  4040.                   the $_ string is searched and modified.  (The string
  4041.                   specified with =~ must be a scalar variable, an
  4042.                   array element, or an assignment to one of those,
  4043.                   i.e. an lvalue.)  If the pattern contains a $ that
  4044.                   looks like a variable rather than an end-of-string
  4045.                   test, the variable will be interpolated into the
  4046.                   pattern at run-time.  If you only want the pattern
  4047.                   compiled once the first time the variable is
  4048.                   interpolated, add an "o" at the end.  If the PATTERN
  4049.                   evaluates to a null string, the most recent
  4050.                   successful regular expression is used instead.  See
  4051.                   also the section on regular expressions.  Examples:
  4052.  
  4053.                       s/\bgreen\b/mauve/g;      # don't change wintergreen
  4054.  
  4055.                       $path =~ s|/usr/bin|/usr/local/bin|;
  4056.  
  4057.                       s/Login: $foo/Login: $bar/; # run-time pattern
  4058.  
  4059.                       ($foo = $bar) =~ s/bar/foo/;
  4060.  
  4061.                       $_ = 'abc123xyz';
  4062.                       s/\d+/$&*2/e;        # yields 'abc246xyz'
  4063.                       s/\d+/sprintf("%5d",$&)/e;     # yields 'abc  246xyz'
  4064.                       s/\w/$& x 2/eg;      # yields 'aabbcc  224466xxyyzz'
  4065.  
  4066.                       s/([^ ]*) *([^ ]*)/$2 $1/;     # reverse 1st two fields
  4067.  
  4068.                   (Note the use of $ instead of \ in the last example.
  4069.                   See section on regular expressions.)
  4070.  
  4071.           scalar(EXPR)
  4072.                   Forces EXPR to be interpreted in a scalar context
  4073.                   and returns the value of EXPR.
  4074.  
  4075.           seek(FILEHANDLE,POSITION,WHENCE)
  4076.                   Randomly positions the file pointer for FILEHANDLE,
  4077.                   just like the fseek() call of stdio.  FILEHANDLE may
  4078.                   be an expression whose value gives the name of the
  4079.                   filehandle.  Returns 1 upon success, 0 otherwise.
  4080.  
  4081.           seekdir(DIRHANDLE,POS)
  4082.                   Sets the current position for the readdir() routine
  4083.                   on DIRHANDLE.  POS must be a value returned by
  4084.                   telldir().  Has the same caveats about possible
  4085.                   directory compaction as the corresponding system
  4086.  
  4087.  
  4088.  
  4089.      Page 62                                         (printed 1/17/94)
  4090.  
  4091.  
  4092.  
  4093.  
  4094.  
  4095.  
  4096.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4097.  
  4098.  
  4099.  
  4100.                   library routine.
  4101.  
  4102.           select(FILEHANDLE)
  4103.  
  4104.           select  Returns the currently selected filehandle.  Sets the
  4105.                   current default filehandle for output, if FILEHANDLE
  4106.                   is supplied.  This has two effects: first, a write
  4107.                   or a print without a filehandle will default to this
  4108.                   FILEHANDLE.  Second, references to variables related
  4109.                   to output will refer to this output channel.  For
  4110.                   example, if you have to set the top of form format
  4111.                   for more than one output channel, you might do the
  4112.                   following:
  4113.  
  4114.                        select(REPORT1);
  4115.                        $^ = 'report1_top';
  4116.                        select(REPORT2);
  4117.                        $^ = 'report2_top';
  4118.  
  4119.                   FILEHANDLE may be an expression whose value gives
  4120.                   the name of the actual filehandle.  Thus:
  4121.  
  4122.                        $oldfh = select(STDERR); $| = 1; select($oldfh);
  4123.  
  4124.  
  4125.           select(RBITS,WBITS,EBITS,TIMEOUT)
  4126.                   This calls the select system call with the bitmasks
  4127.                   specified, which can be constructed using fileno()
  4128.                   and vec(), along these lines:
  4129.  
  4130.                        $rin = $win = $ein = '';
  4131.                        vec($rin,fileno(STDIN),1) = 1;
  4132.                        vec($win,fileno(STDOUT),1) = 1;
  4133.                        $ein = $rin | $win;
  4134.  
  4135.                   If you want to select on many filehandles you might
  4136.                   wish to write a subroutine:
  4137.  
  4138.                        sub fhbits {
  4139.                            local(@fhlist) = split(' ',$_[0]);
  4140.                            local($bits);
  4141.                            for (@fhlist) {
  4142.                             vec($bits,fileno($_),1) = 1;
  4143.                            }
  4144.                            $bits;
  4145.                        }
  4146.                        $rin = &fhbits('STDIN TTY SOCK');
  4147.  
  4148.                   The usual idiom is:
  4149.  
  4150.                        ($nfound,$timeleft) =
  4151.                          select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  4152.  
  4153.  
  4154.  
  4155.      Page 63                                         (printed 1/17/94)
  4156.  
  4157.  
  4158.  
  4159.  
  4160.  
  4161.  
  4162.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4163.  
  4164.  
  4165.  
  4166.                   or to block until something becomes ready:
  4167.  
  4168.                        $nfound = select($rout=$rin, $wout=$win,
  4169.                                       $eout=$ein, undef);
  4170.  
  4171.                   Any of the bitmasks can also be undef.  The timeout,
  4172.                   if specified, is in seconds, which may be
  4173.                   fractional.  NOTE: not all implementations are
  4174.                   capable of returning the $timeleft.  If not, they
  4175.                   always return $timeleft equal to the supplied
  4176.                   $timeout.
  4177.  
  4178.           semctl(ID,SEMNUM,CMD,ARG)
  4179.                   Calls the System V IPC function semctl.  If CMD is
  4180.                   &IPC_STAT or &GETALL, then ARG must be a variable
  4181.                   which will hold the returned semid_ds structure or
  4182.                   semaphore value array.  Returns like ioctl: the
  4183.                   undefined value for error, "0 but true" for zero, or
  4184.                   the actual return value otherwise.
  4185.  
  4186.           semget(KEY,NSEMS,SIZE,FLAGS)
  4187.                   Calls the System V IPC function semget.  Returns the
  4188.                   semaphore id, or the undefined value if there is an
  4189.                   error.
  4190.  
  4191.           semop(KEY,OPSTRING)
  4192.                   Calls the System V IPC function semop to perform
  4193.                   semaphore operations such as signaling and waiting.
  4194.                   OPSTRING must be a packed array of semop structures.
  4195.                   Each semop structure can be generated with
  4196.                   'pack("sss", $semnum, $semop, $semflag)'.  The
  4197.                   number of semaphore operations is implied by the
  4198.                   length of OPSTRING.  Returns true if successful, or
  4199.                   false if there is an error.  As an example, the
  4200.                   following code waits on semaphore $semnum of
  4201.                   semaphore id $semid:
  4202.  
  4203.                        $semop = pack("sss", $semnum, -1, 0);
  4204.                        die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  4205.  
  4206.                   To signal the semaphore, replace "-1" with "1".
  4207.  
  4208.           send(SOCKET,MSG,FLAGS,TO)
  4209.  
  4210.           send(SOCKET,MSG,FLAGS)
  4211.                   Sends a message on a socket.  Takes the same flags
  4212.                   as the system call of the same name.  On unconnected
  4213.                   sockets you must specify a destination to send TO.
  4214.                   Returns the number of characters sent, or the
  4215.                   undefined value if there is an error.
  4216.  
  4217.  
  4218.  
  4219.  
  4220.  
  4221.      Page 64                                         (printed 1/17/94)
  4222.  
  4223.  
  4224.  
  4225.  
  4226.  
  4227.  
  4228.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4229.  
  4230.  
  4231.  
  4232.           setpgrp(PID,PGRP)
  4233.                   Sets the current process group for the specified
  4234.                   PID, 0 for the current process.  Will produce a
  4235.                   fatal error if used on a machine that doesn't
  4236.                   implement setpgrp(2).
  4237.  
  4238.           setpriority(WHICH,WHO,PRIORITY)
  4239.                   Sets the current priority for a process, a process
  4240.                   group, or a user.  (See setpriority(2).)  Will
  4241.                   produce a fatal error if used on a machine that
  4242.                   doesn't implement setpriority(2).
  4243.  
  4244.           setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
  4245.                   Sets the socket option requested.  Returns undefined
  4246.                   if there is an error.  OPTVAL may be specified as
  4247.                   undef if you don't want to pass an argument.
  4248.  
  4249.           shift(ARRAY)
  4250.  
  4251.           shift ARRAY
  4252.  
  4253.           shift   Shifts the first value of the array off and returns
  4254.                   it, shortening the array by 1 and moving everything
  4255.                   down.  If there are no elements in the array,
  4256.                   returns the undefined value.  If ARRAY is omitted,
  4257.                   shifts the @ARGV array in the main program, and the
  4258.                   @_ array in subroutines.  (This is determined
  4259.                   lexically.)  See also unshift(), push() and pop().
  4260.                   Shift() and unshift() do the same thing to the left
  4261.                   end of an array that push() and pop() do to the
  4262.                   right end.
  4263.  
  4264.           shmctl(ID,CMD,ARG)
  4265.                   Calls the System V IPC function shmctl.  If CMD is
  4266.                   &IPC_STAT, then ARG must be a variable which will
  4267.                   hold the returned shmid_ds structure.  Returns like
  4268.                   ioctl: the undefined value for error, "0 but true"
  4269.                   for zero, or the actual return value otherwise.
  4270.  
  4271.           shmget(KEY,SIZE,FLAGS)
  4272.                   Calls the System V IPC function shmget.  Returns the
  4273.                   shared memory segment id, or the undefined value if
  4274.                   there is an error.
  4275.  
  4276.           shmread(ID,VAR,POS,SIZE)
  4277.  
  4278.           shmwrite(ID,STRING,POS,SIZE)
  4279.                   Reads or writes the System V shared memory segment
  4280.                   ID starting at position POS for size SIZE by
  4281.                   attaching to it, copying in/out, and detaching from
  4282.                   it.  When reading, VAR must be a variable which will
  4283.                   hold the data read.  When writing, if STRING is too
  4284.  
  4285.  
  4286.  
  4287.      Page 65                                         (printed 1/17/94)
  4288.  
  4289.  
  4290.  
  4291.  
  4292.  
  4293.  
  4294.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4295.  
  4296.  
  4297.  
  4298.                   long, only SIZE bytes are used; if STRING is too
  4299.                   short, nulls are written to fill out SIZE bytes.
  4300.                   Return true if successful, or false if there is an
  4301.                   error.
  4302.  
  4303.           shutdown(SOCKET,HOW)
  4304.                   Shuts down a socket connection in the manner
  4305.                   indicated by HOW, which has the same interpretation
  4306.                   as in the system call of the same name.
  4307.  
  4308.           sin(EXPR)
  4309.  
  4310.           sin EXPR
  4311.                   Returns the sine of EXPR (expressed in radians).  If
  4312.                   EXPR is omitted, returns sine of $_.
  4313.  
  4314.           sleep(EXPR)
  4315.  
  4316.           sleep EXPR
  4317.  
  4318.           sleep   Causes the script to sleep for EXPR seconds, or
  4319.                   forever if no EXPR.  May be interrupted by sending
  4320.                   the process a SIGALRM.  Returns the number of
  4321.                   seconds actually slept.  You probably cannot mix
  4322.                   alarm() and sleep() calls, since sleep() is often
  4323.                   implemented using alarm().
  4324.  
  4325.           socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
  4326.                   Opens a socket of the specified kind and attaches it
  4327.                   to filehandle SOCKET.  DOMAIN, TYPE and PROTOCOL are
  4328.                   specified the same as for the system call of the
  4329.                   same name.  You may need to run h2ph on sys/socket.h
  4330.                   to get the proper values handy in a perl library
  4331.                   file.  Return true if successful.  See the example
  4332.                   in the section on Interprocess Communication.
  4333.  
  4334.           socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
  4335.                   Creates an unnamed pair of sockets in the specified
  4336.                   domain, of the specified type.  DOMAIN, TYPE and
  4337.                   PROTOCOL are specified the same as for the system
  4338.                   call of the same name.  If unimplemented, yields a
  4339.                   fatal error.  Return true if successful.
  4340.  
  4341.           sort(SUBROUTINE LIST)
  4342.  
  4343.           sort(LIST)
  4344.  
  4345.           sort SUBROUTINE LIST
  4346.  
  4347.           sort BLOCK LIST
  4348.  
  4349.  
  4350.  
  4351.  
  4352.  
  4353.      Page 66                                         (printed 1/17/94)
  4354.  
  4355.  
  4356.  
  4357.  
  4358.  
  4359.  
  4360.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4361.  
  4362.  
  4363.  
  4364.           sort LIST
  4365.                   Sorts the LIST and returns the sorted array value.
  4366.                   Nonexistent values of arrays are stripped out.  If
  4367.                   SUBROUTINE or BLOCK is omitted, sorts in standard
  4368.                   string comparison order.  If SUBROUTINE is
  4369.                   specified, gives the name of a subroutine that
  4370.                   returns an integer less than, equal to, or greater
  4371.                   than 0, depending on how the elements of the array
  4372.                   are to be ordered.  (The <=> and cmp operators are
  4373.                   extremely useful in such routines.)  SUBROUTINE may
  4374.                   be a scalar variable name, in which case the value
  4375.                   provides the name of the subroutine to use.  In
  4376.                   place of a SUBROUTINE name, you can provide a BLOCK
  4377.                   as an anonymous, in-line sort subroutine.
  4378.  
  4379.                   In the interests of efficiency the normal calling
  4380.                   code for subroutines is bypassed, with the following
  4381.                   effects: the subroutine may not be a recursive
  4382.                   subroutine, and the two elements to be compared are
  4383.                   passed into the subroutine not via @_ but as $a and
  4384.                   $b (see example below).  They are passed by
  4385.                   reference so don't modify $a and $b.
  4386.  
  4387.                   Examples:
  4388.  
  4389.                        # sort lexically
  4390.                        @articles = sort @files;
  4391.  
  4392.                        # same thing, but with explicit sort routine
  4393.                        @articles = sort {$a cmp $b} @files;
  4394.  
  4395.                        # same thing in reversed order
  4396.                        @articles = sort {$b cmp $a} @files;
  4397.  
  4398.                        # sort numerically ascending
  4399.                        @articles = sort {$a <=> $b} @files;
  4400.  
  4401.                        # sort numerically descending
  4402.                        @articles = sort {$b <=> $a} @files;
  4403.  
  4404.                        # sort using explicit subroutine name
  4405.                        sub byage {
  4406.                            $age{$a} <=> $age{$b};    # presuming integers
  4407.                        }
  4408.                        @sortedclass = sort byage @class;
  4409.  
  4410.  
  4411.  
  4412.  
  4413.  
  4414.  
  4415.  
  4416.  
  4417.  
  4418.  
  4419.      Page 67                                         (printed 1/17/94)
  4420.  
  4421.  
  4422.  
  4423.  
  4424.  
  4425.  
  4426.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4427.  
  4428.  
  4429.  
  4430.                        sub reverse { $b cmp $a; }
  4431.                        @harry = ('dog','cat','x','Cain','Abel');
  4432.                        @george = ('gone','chased','yz','Punished','Axed');
  4433.                        print sort @harry;
  4434.                             # prints AbelCaincatdogx
  4435.                        print sort reverse @harry;
  4436.                             # prints xdogcatCainAbel
  4437.                        print sort @george, 'to', @harry;
  4438.                             # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  4439.  
  4440.  
  4441.           splice(ARRAY,OFFSET,LENGTH,LIST)
  4442.  
  4443.           splice(ARRAY,OFFSET,LENGTH)
  4444.  
  4445.           splice(ARRAY,OFFSET)
  4446.                   Removes the elements designated by OFFSET and LENGTH
  4447.                   from an array, and replaces them with the elements
  4448.                   of LIST, if any.  Returns the elements removed from
  4449.                   the array.  The array grows or shrinks as necessary.
  4450.                   If LENGTH is omitted, removes everything from OFFSET
  4451.                   onward.  The following equivalencies hold (assuming
  4452.                   $[ == 0):
  4453.  
  4454.                        push(@a,$x,$y)                splice(@a,$#a+1,0,$x,$y)
  4455.                        pop(@a)                       splice(@a,-1)
  4456.                        shift(@a)                     splice(@a,0,1)
  4457.                        unshift(@a,$x,$y)             splice(@a,0,0,$x,$y)
  4458.                        $a[$x] = $y                   splice(@a,$x,1,$y);
  4459.  
  4460.                   Example, assuming array lengths are passed before arrays:
  4461.  
  4462.                        sub aeq { # compare two array values
  4463.                             local(@a) = splice(@_,0,shift);
  4464.                             local(@b) = splice(@_,0,shift);
  4465.                             return 0 unless @a == @b;     # same len?
  4466.                             while (@a) {
  4467.                                 return 0 if pop(@a) ne pop(@b);
  4468.                             }
  4469.                             return 1;
  4470.                        }
  4471.                        if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  4472.  
  4473.  
  4474.           split(/PATTERN/,EXPR,LIMIT)
  4475.  
  4476.  
  4477.  
  4478.  
  4479.  
  4480.  
  4481.  
  4482.  
  4483.  
  4484.  
  4485.      Page 68                                         (printed 1/17/94)
  4486.  
  4487.  
  4488.  
  4489.  
  4490.  
  4491.  
  4492.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4493.  
  4494.  
  4495.  
  4496.           split(/PATTERN/,EXPR)
  4497.  
  4498.           split(/PATTERN/)
  4499.  
  4500.           split   Splits a string into an array of strings, and
  4501.                   returns it.  (If not in an array context, returns
  4502.                   the number of fields found and splits into the @_
  4503.                   array.  (In an array context, you can force the
  4504.                   split into @_ by using ?? as the pattern delimiters,
  4505.                   but it still returns the array value.))  If EXPR is
  4506.                   omitted, splits the $_ string.  If PATTERN is also
  4507.                   omitted, splits on whitespace (/[ \t\n]+/).
  4508.                   Anything matching PATTERN is taken to be a delimiter
  4509.                   separating the fields.  (Note that the delimiter may
  4510.                   be longer than one character.)  If LIMIT is
  4511.                   specified, splits into no more than that many fields
  4512.                   (though it may split into fewer).  If LIMIT is
  4513.                   unspecified, trailing null fields are stripped
  4514.                   (which potential users of pop() would do well to
  4515.                   remember).  A pattern matching the null string (not
  4516.                   to be confused with a null pattern //, which is just
  4517.                   one member of the set of patterns matching a null
  4518.                   string) will split the value of EXPR into separate
  4519.                   characters at each point it matches that way.  For
  4520.                   example:
  4521.  
  4522.                        print join(':', split(/ */, 'hi there'));
  4523.  
  4524.                   produces the output 'h:i:t:h:e:r:e'.
  4525.  
  4526.                   The LIMIT parameter can be used to partially split a
  4527.                   line
  4528.  
  4529.                        ($login, $passwd, $remainder) = split(/:/, $_, 3);
  4530.  
  4531.                   (When assigning to a list, if LIMIT is omitted, perl
  4532.                   supplies a LIMIT one larger than the number of
  4533.                   variables in the list, to avoid unnecessary work.
  4534.                   For the list above LIMIT would have been 4 by
  4535.                   default.  In time critical applications it behooves
  4536.                   you not to split into more fields than you really
  4537.                   need.)
  4538.  
  4539.                   If the PATTERN contains parentheses, additional
  4540.                   array elements are created from each matching
  4541.                   substring in the delimiter.
  4542.  
  4543.                        split(/([,-])/,"1-10,20");
  4544.  
  4545.                   produces the array value
  4546.  
  4547.                        (1,'-',10,',',20)
  4548.  
  4549.  
  4550.  
  4551.      Page 69                                         (printed 1/17/94)
  4552.  
  4553.  
  4554.  
  4555.  
  4556.  
  4557.  
  4558.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4559.  
  4560.  
  4561.  
  4562.                   The pattern /PATTERN/ may be replaced with an
  4563.                   expression to specify patterns that vary at runtime.
  4564.                   (To do runtime compilation only once, use
  4565.                   /$variable/o.)  As a special case, specifying a
  4566.                   space (' ') will split on white space just as split
  4567.                   with no arguments does, but leading white space does
  4568.                   NOT produce a null first field.  Thus, split(' ')
  4569.                   can be used to emulate awk's default behavior,
  4570.                   whereas split(/ /) will give you as many null
  4571.                   initial fields as there are leading spaces.
  4572.  
  4573.                   Example:
  4574.  
  4575.                        open(passwd, '/etc/passwd');
  4576.                        while (<passwd>) {
  4577.                             ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  4578.                                  = split(/:/);
  4579.                             ...
  4580.                        }
  4581.  
  4582.                   (Note that $shell above will still have a newline on
  4583.                   it.  See chop().)  See also join.
  4584.  
  4585.           sprintf(FORMAT,LIST)
  4586.                   Returns a string formatted by the usual printf
  4587.                   conventions.  The * character is not supported.
  4588.  
  4589.           sqrt(EXPR)
  4590.  
  4591.           sqrt EXPR
  4592.                   Return the square root of EXPR.  If EXPR is omitted,
  4593.                   returns square root of $_.
  4594.  
  4595.           srand(EXPR)
  4596.  
  4597.           srand EXPR
  4598.                   Sets the random number seed for the rand operator.
  4599.                   If EXPR is omitted, does srand(time).
  4600.  
  4601.           stat(FILEHANDLE)
  4602.  
  4603.           stat FILEHANDLE
  4604.  
  4605.           stat(EXPR)
  4606.  
  4607.           stat SCALARVARIABLE
  4608.                   Returns a 13-element array giving the statistics for
  4609.                   a file, either the file opened via FILEHANDLE, or
  4610.                   named by EXPR.  Returns a null list if the stat
  4611.                   fails.  Typically used as follows:
  4612.  
  4613.  
  4614.  
  4615.  
  4616.  
  4617.      Page 70                                         (printed 1/17/94)
  4618.  
  4619.  
  4620.  
  4621.  
  4622.  
  4623.  
  4624.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4625.  
  4626.  
  4627.  
  4628.                       ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  4629.                          $atime,$mtime,$ctime,$blksize,$blocks)
  4630.                              = stat($filename);
  4631.  
  4632.                   If stat is passed the special filehandle consisting
  4633.                   of an underline, no stat is done, but the current
  4634.                   contents of the stat structure from the last stat or
  4635.                   filetest are returned.  Example:
  4636.  
  4637.                        if (-x $file && (($d) = stat(_)) && $d < 0) {
  4638.                             print "$file is executable NFS file\n";
  4639.                        }
  4640.  
  4641.                   (This only works on machines for which the device
  4642.                   number is negative under NFS.)
  4643.  
  4644.           study(SCALAR)
  4645.  
  4646.           study SCALAR
  4647.  
  4648.           study   Takes extra time to study SCALAR ($_ if unspecified)
  4649.                   in anticipation of doing many pattern matches on the
  4650.                   string before it is next modified.  This may or may
  4651.                   not save time, depending on the nature and number of
  4652.                   patterns you are searching on, and on the
  4653.                   distribution of character frequencies in the string
  4654.                   to be searched--you probably want to compare
  4655.                   runtimes with and without it to see which runs
  4656.                   faster.  Those loops which scan for many short
  4657.                   constant strings (including the constant parts of
  4658.                   more complex patterns) will benefit most.  You may
  4659.                   have only one study active at a time--if you study a
  4660.                   different scalar the first is "unstudied".  (The way
  4661.                   study works is this: a linked list of every
  4662.                   character in the string to be searched is made, so
  4663.                   we know, for example, where all the 'k' characters
  4664.                   are.  From each search string, the rarest character
  4665.                   is selected, based on some static frequency tables
  4666.                   constructed from some C programs and English text.
  4667.                   Only those places that contain this "rarest"
  4668.                   character are examined.)
  4669.  
  4670.                   For example, here is a loop which inserts index
  4671.                   producing entries before any line containing a
  4672.                   certain pattern:
  4673.  
  4674.  
  4675.  
  4676.  
  4677.  
  4678.  
  4679.  
  4680.  
  4681.  
  4682.  
  4683.      Page 71                                         (printed 1/17/94)
  4684.  
  4685.  
  4686.  
  4687.  
  4688.  
  4689.  
  4690.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4691.  
  4692.  
  4693.  
  4694.                        while (<>) {
  4695.                             study;
  4696.                             print ".IX foo\n" if /\bfoo\b/;
  4697.                             print ".IX bar\n" if /\bbar\b/;
  4698.                             print ".IX blurfl\n" if /\bblurfl\b/;
  4699.                             ...
  4700.                             print;
  4701.                        }
  4702.  
  4703.                   In searching for /\bfoo\b/, only those locations in
  4704.                   $_ that contain 'f' will be looked at, because 'f'
  4705.                   is rarer than 'o'.  In general, this is a big win
  4706.                   except in pathological cases.  The only question is
  4707.                   whether it saves you more time than it took to build
  4708.                   the linked list in the first place.
  4709.  
  4710.                   Note that if you have to look for strings that you
  4711.                   don't know till runtime, you can build an entire
  4712.                   loop as a string and eval that to avoid recompiling
  4713.                   all your patterns all the time.  Together with
  4714.                   undefining $/ to input entire files as one record,
  4715.                   this can be very fast, often faster than specialized
  4716.                   programs like fgrep.  The following scans a list of
  4717.                   files (@files) for a list of words (@words), and
  4718.                   prints out the names of those files that contain a
  4719.                   match:
  4720.  
  4721.                        $search = 'while (<>) { study;';
  4722.                        foreach $word (@words) {
  4723.                            $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n";
  4724.                        }
  4725.                        $search .= "}";
  4726.                        @ARGV = @files;
  4727.                        undef $/;
  4728.                        eval $search;       # this screams
  4729.                        $/ = "\n";          # put back to normal input delim
  4730.                        foreach $file (sort keys(%seen)) {
  4731.                            print $file, "\n";
  4732.                        }
  4733.  
  4734.  
  4735.           substr(EXPR,OFFSET,LEN)
  4736.  
  4737.           substr(EXPR,OFFSET)
  4738.                   Extracts a substring out of EXPR and returns it.
  4739.                   First character is at offset 0, or whatever you've
  4740.                   set $[ to.  If OFFSET is negative, starts that far
  4741.                   from the end of the string.  If LEN is omitted,
  4742.                   returns everything to the end of the string.  You
  4743.                   can use the substr() function as an lvalue, in which
  4744.                   case EXPR must be an lvalue.  If you assign
  4745.                   something shorter than LEN, the string will shrink,
  4746.  
  4747.  
  4748.  
  4749.      Page 72                                         (printed 1/17/94)
  4750.  
  4751.  
  4752.  
  4753.  
  4754.  
  4755.  
  4756.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4757.  
  4758.  
  4759.  
  4760.                   and if you assign something longer than LEN, the
  4761.                   string will grow to accommodate it.  To keep the
  4762.                   string the same length you may need to pad or chop
  4763.                   your value using sprintf().
  4764.  
  4765.           symlink(OLDFILE,NEWFILE)
  4766.                   Creates a new filename symbolically linked to the
  4767.                   old filename.  Returns 1 for success, 0 otherwise.
  4768.                   On systems that don't support symbolic links,
  4769.                   produces a fatal error at run time.  To check for
  4770.                   that, use eval:
  4771.  
  4772.                        $symlink_exists = (eval 'symlink("","");', $@ eq '');
  4773.  
  4774.  
  4775.           syscall(LIST)
  4776.  
  4777.           syscall LIST
  4778.                   Calls the system call specified as the first element
  4779.                   of the list, passing the remaining elements as
  4780.                   arguments to the system call.  If unimplemented,
  4781.                   produces a fatal error.  The arguments are
  4782.                   interpreted as follows: if a given argument is
  4783.                   numeric, the argument is passed as an int.  If not,
  4784.                   the pointer to the string value is passed.  You are
  4785.                   responsible to make sure a string is pre-extended
  4786.                   long enough to receive any result that might be
  4787.                   written into a string.  If your integer arguments
  4788.                   are not literals and have never been interpreted in
  4789.                   a numeric context, you may need to add 0 to them to
  4790.                   force them to look like numbers.
  4791.  
  4792.                        require 'syscall.ph';         # may need to run h2ph
  4793.                        syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  4794.  
  4795.  
  4796.           sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  4797.  
  4798.           sysread(FILEHANDLE,SCALAR,LENGTH)
  4799.                   Attempts to read LENGTH bytes of data into variable
  4800.                   SCALAR from the specified FILEHANDLE, using the
  4801.                   system call read(2).  It bypasses stdio, so mixing
  4802.                   this with other kinds of reads may cause confusion.
  4803.                   Returns the number of bytes actually read, or undef
  4804.                   if there was an error.  SCALAR will be grown or
  4805.                   shrunk to the length actually read.  An OFFSET may
  4806.                   be specified to place the read data at some other
  4807.                   place than the beginning of the string.
  4808.  
  4809.  
  4810.  
  4811.  
  4812.  
  4813.  
  4814.  
  4815.      Page 73                                         (printed 1/17/94)
  4816.  
  4817.  
  4818.  
  4819.  
  4820.  
  4821.  
  4822.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4823.  
  4824.  
  4825.  
  4826.           system(LIST)
  4827.  
  4828.           system LIST
  4829.                   Does exactly the same thing as "exec LIST" except
  4830.                   that a fork is done first, and the parent process
  4831.                   waits for the child process to complete.  Note that
  4832.                   argument processing varies depending on the number
  4833.                   of arguments.  The return value is the exit status
  4834.                   of the program as returned by the wait() call.  To
  4835.                   get the actual exit value divide by 256.  See also
  4836.                   exec.
  4837.  
  4838.           syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  4839.  
  4840.           syswrite(FILEHANDLE,SCALAR,LENGTH)
  4841.                   Attempts to write LENGTH bytes of data from variable
  4842.                   SCALAR to the specified FILEHANDLE, using the system
  4843.                   call write(2).  It bypasses stdio, so mixing this
  4844.                   with prints may cause confusion.  Returns the number
  4845.                   of bytes actually written, or undef if there was an
  4846.                   error.  An OFFSET may be specified to place the read
  4847.                   data at some other place than the beginning of the
  4848.                   string.
  4849.  
  4850.           tell(FILEHANDLE)
  4851.  
  4852.           tell FILEHANDLE
  4853.  
  4854.           tell    Returns the current file position for FILEHANDLE.
  4855.                   FILEHANDLE may be an expression whose value gives
  4856.                   the name of the actual filehandle.  If FILEHANDLE is
  4857.                   omitted, assumes the file last read.
  4858.  
  4859.           telldir(DIRHANDLE)
  4860.  
  4861.           telldir DIRHANDLE
  4862.                   Returns the current position of the readdir()
  4863.                   routines on DIRHANDLE.  Value may be given to
  4864.                   seekdir() to access a particular location in a
  4865.                   directory.  Has the same caveats about possible
  4866.                   directory compaction as the corresponding system
  4867.                   library routine.
  4868.  
  4869.           time    Returns the number of non-leap seconds since
  4870.                   00:00:00 UTC, January 1, 1970.  Suitable for feeding
  4871.                   to gmtime() and localtime().
  4872.  
  4873.           times   Returns a four-element array giving the user and
  4874.                   system times, in seconds, for this process and the
  4875.                   children of this process.
  4876.  
  4877.                       ($user,$system,$cuser,$csystem) = times;
  4878.  
  4879.  
  4880.  
  4881.      Page 74                                         (printed 1/17/94)
  4882.  
  4883.  
  4884.  
  4885.  
  4886.  
  4887.  
  4888.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4889.  
  4890.  
  4891.  
  4892.           tr/SEARCHLIST/REPLACEMENTLIST/cds
  4893.  
  4894.           y/SEARCHLIST/REPLACEMENTLIST/cds
  4895.                   Translates all occurrences of the characters found
  4896.                   in the search list with the corresponding character
  4897.                   in the replacement list.  It returns the number of
  4898.                   characters replaced or deleted.  If no string is
  4899.                   specified via the =~ or !~ operator, the $_ string
  4900.                   is translated.  (The string specified with =~ must
  4901.                   be a scalar variable, an array element, or an
  4902.                   assignment to one of those, i.e. an lvalue.)  For
  4903.                   sed devotees, y is provided as a synonym for tr.  If
  4904.                   the SEARCHLIST is delimited by bracketing quotes,
  4905.                   the REPLACEMENTLIST has its own pair of quotes,
  4906.                   which may or may not be bracketing quotes, e.g.
  4907.                   tr[A-Z][a-z] or tr(+-*/)/ABCD/.
  4908.  
  4909.                   If the c modifier is specified, the SEARCHLIST
  4910.                   character set is complemented.  If the d modifier is
  4911.                   specified, any characters specified by SEARCHLIST
  4912.                   that are not found in REPLACEMENTLIST are deleted.
  4913.                   (Note that this is slightly more flexible than the
  4914.                   behavior of some tr programs, which delete anything
  4915.                   they find in the SEARCHLIST, period.)  If the s
  4916.                   modifier is specified, sequences of characters that
  4917.                   were translated to the same character are squashed
  4918.                   down to 1 instance of the character.
  4919.  
  4920.                   If the d modifier was used, the REPLACEMENTLIST is
  4921.                   always interpreted exactly as specified.  Otherwise,
  4922.                   if the REPLACEMENTLIST is shorter than the
  4923.                   SEARCHLIST, the final character is replicated till
  4924.                   it is long enough.  If the REPLACEMENTLIST is null,
  4925.                   the SEARCHLIST is replicated.  This latter is useful
  4926.                   for counting characters in a class, or for squashing
  4927.                   character sequences in a class.
  4928.  
  4929.                   Examples:
  4930.  
  4931.                       $ARGV[1] =~ y/A-Z/a-z/;   # canonicalize to lower case
  4932.  
  4933.                       $cnt = tr/*/*/;           # count the stars in $_
  4934.  
  4935.                       $cnt = tr/0-9//;          # count the digits in $_
  4936.  
  4937.                       tr/a-zA-Z//s;             # bookkeeper -> bokeper
  4938.  
  4939.                       ($HOST = $host) =~ tr/a-z/A-Z/;
  4940.  
  4941.                       y/a-zA-Z/ /cs;            # change non-alphas to single space
  4942.  
  4943.                       tr/\200-\377/\0-\177/;    # delete 8th bit
  4944.  
  4945.  
  4946.  
  4947.      Page 75                                         (printed 1/17/94)
  4948.  
  4949.  
  4950.  
  4951.  
  4952.  
  4953.  
  4954.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  4955.  
  4956.  
  4957.  
  4958.           truncate(FILEHANDLE,LENGTH)
  4959.  
  4960.           truncate(EXPR,LENGTH)
  4961.                   Truncates the file opened on FILEHANDLE, or named by
  4962.                   EXPR, to the specified length.  Produces a fatal
  4963.                   error if truncate isn't implemented on your system.
  4964.  
  4965.           umask(EXPR)
  4966.  
  4967.           umask EXPR
  4968.  
  4969.           umask   Sets the umask for the process and returns the old
  4970.                   one.  If EXPR is omitted, merely returns current
  4971.                   umask.
  4972.  
  4973.           undef(EXPR)
  4974.  
  4975.           undef EXPR
  4976.  
  4977.           undef   Undefines the value of EXPR, which must be an
  4978.                   lvalue.  Use only on a scalar value, an entire
  4979.                   array, or a subroutine name (using &).  (Undef will
  4980.                   probably not do what you expect on most predefined
  4981.                   variables or dbm array values.)  Always returns the
  4982.                   undefined value.  You can omit the EXPR, in which
  4983.                   case nothing is undefined, but you still get an
  4984.                   undefined value that you could, for instance, return
  4985.                   from a subroutine.  Examples:
  4986.  
  4987.                        undef $foo;
  4988.                        undef $bar{'blurfl'};
  4989.                        undef @ary;
  4990.                        undef %assoc;
  4991.                        undef &mysub;
  4992.                        return (wantarray ? () : undef) if $they_blew_it;
  4993.  
  4994.  
  4995.           unlink(LIST)
  4996.  
  4997.           unlink LIST
  4998.                   Deletes a list of files.  Returns the number of
  4999.                   files successfully deleted.
  5000.  
  5001.                        $cnt = unlink 'a', 'b', 'c';
  5002.                        unlink @goners;
  5003.                        unlink <*.bak>;
  5004.  
  5005.                   Note: unlink will not delete directories unless you
  5006.                   are superuser and the ----UUUU flag is supplied to perl.
  5007.                   Even if these conditions are met, be warned that
  5008.                   unlinking a directory can inflict damage on your
  5009.                   filesystem.  Use rmdir instead.
  5010.  
  5011.  
  5012.  
  5013.      Page 76                                         (printed 1/17/94)
  5014.  
  5015.  
  5016.  
  5017.  
  5018.  
  5019.  
  5020.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5021.  
  5022.  
  5023.  
  5024.           unpack(TEMPLATE,EXPR)
  5025.                   Unpack does the reverse of pack: it takes a string
  5026.                   representing a structure and expands it out into an
  5027.                   array value, returning the array value.  (In a
  5028.                   scalar context, it merely returns the first value
  5029.                   produced.)  The TEMPLATE has the same format as in
  5030.                   the pack function.  Here's a subroutine that does
  5031.                   substring:
  5032.  
  5033.                        sub substr {
  5034.                             local($what,$where,$howmuch) = @_;
  5035.                             unpack("x$where a$howmuch", $what);
  5036.                        }
  5037.  
  5038.                   and then there's
  5039.  
  5040.                        sub ord { unpack("c",$_[0]); }
  5041.  
  5042.                   In addition, you may prefix a field with a %<number>
  5043.                   to indicate that you want a <number>-bit checksum of
  5044.                   the items instead of the items themselves.  Default
  5045.                   is a 16-bit checksum.  For example, the following
  5046.                   computes the same number as the System V sum
  5047.                   program:
  5048.  
  5049.                        while (<>) {
  5050.                            $checksum += unpack("%16C*", $_);
  5051.                        }
  5052.                        $checksum %= 65536;
  5053.  
  5054.  
  5055.           unshift(ARRAY,LIST)
  5056.                   Does the opposite of a shift.  Or the opposite of a
  5057.                   push, depending on how you look at it.  Prepends
  5058.                   list to the front of the array, and returns the
  5059.                   number of elements in the new array.
  5060.  
  5061.                        unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  5062.  
  5063.  
  5064.           utime(LIST)
  5065.  
  5066.           utime LIST
  5067.                   Changes the access and modification times on each
  5068.                   file of a list of files.  The first two elements of
  5069.                   the list must be the NUMERICAL access and
  5070.                   modification times, in that order.  Returns the
  5071.                   number of files successfully changed.  The inode
  5072.                   modification time of each file is set to the current
  5073.                   time.  Example of a "touch" command:
  5074.  
  5075.  
  5076.  
  5077.  
  5078.  
  5079.      Page 77                                         (printed 1/17/94)
  5080.  
  5081.  
  5082.  
  5083.  
  5084.  
  5085.  
  5086.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5087.  
  5088.  
  5089.  
  5090.                        #!/usr/bin/perl
  5091.                        $now = time;
  5092.                        utime $now, $now, @ARGV;
  5093.  
  5094.  
  5095.           values(ASSOC_ARRAY)
  5096.  
  5097.           values ASSOC_ARRAY
  5098.                   Returns a normal array consisting of all the values
  5099.                   of the named associative array.  The values are
  5100.                   returned in an apparently random order, but it is
  5101.                   the same order as either the keys() or each()
  5102.                   function would produce on the same array.  See also
  5103.                   keys() and each().
  5104.  
  5105.           vec(EXPR,OFFSET,BITS)
  5106.                   Treats a string as a vector of unsigned integers,
  5107.                   and returns the value of the bitfield specified.
  5108.                   May also be assigned to.  BITS must be a power of
  5109.                   two from 1 to 32.
  5110.  
  5111.                   Vectors created with vec() can also be manipulated
  5112.                   with the logical operators |, & and ^, which will
  5113.                   assume a bit vector operation is desired when both
  5114.                   operands are strings.  This interpretation is not
  5115.                   enabled unless there is at least one vec() in your
  5116.                   program, to protect older programs.
  5117.  
  5118.                   To transform a bit vector into a string or array of
  5119.                   0's and 1's, use these:
  5120.  
  5121.                        $bits = unpack("b*", $vector);
  5122.                        @bits = split(//, unpack("b*", $vector));
  5123.  
  5124.                   If you know the exact length in bits, it can be used
  5125.                   in place of the *.
  5126.  
  5127.           wait    Waits for a child process to terminate and returns
  5128.                   the pid of the deceased process, or -1 if there are
  5129.                   no child processes.  The status is returned in $?.
  5130.  
  5131.           waitpid(PID,FLAGS)
  5132.                   Waits for a particular child process to terminate
  5133.                   and returns the pid of the deceased process, or -1
  5134.                   if there is no such child process.  The status is
  5135.                   returned in $?.  If you say
  5136.  
  5137.                        require "sys/wait.h";
  5138.                        ...
  5139.                        waitpid(-1,&WNOHANG);
  5140.  
  5141.                   then you can do a non-blocking wait for any process.
  5142.  
  5143.  
  5144.  
  5145.      Page 78                                         (printed 1/17/94)
  5146.  
  5147.  
  5148.  
  5149.  
  5150.  
  5151.  
  5152.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5153.  
  5154.  
  5155.  
  5156.                   Non-blocking wait is only available on machines
  5157.                   supporting either the waitpid (2) or wait4 (2)
  5158.                   system calls.  However, waiting for a particular pid
  5159.                   with FLAGS of 0 is implemented everywhere.  (Perl
  5160.                   emulates the system call by remembering the status
  5161.                   values of processes that have exited but have not
  5162.                   been harvested by the Perl script yet.)
  5163.  
  5164.           wantarray
  5165.                   Returns true if the context of the currently
  5166.                   executing subroutine is looking for an array value.
  5167.                   Returns false if the context is looking for a
  5168.                   scalar.
  5169.  
  5170.                        return wantarray ? () : undef;
  5171.  
  5172.  
  5173.           warn(LIST)
  5174.  
  5175.           warn LIST
  5176.                   Produces a message on STDERR just like "die", but
  5177.                   doesn't exit.
  5178.  
  5179.           write(FILEHANDLE)
  5180.  
  5181.           write(EXPR)
  5182.  
  5183.           write   Writes a formatted record (possibly multi-line) to
  5184.                   the specified file, using the format associated with
  5185.                   that file.  By default the format for a file is the
  5186.                   one having the same name is the filehandle, but the
  5187.                   format for the current output channel (see select)
  5188.                   may be set explicitly by assigning the name of the
  5189.                   format to the $~ variable.
  5190.  
  5191.                   Top of form processing is handled automatically: if
  5192.                   there is insufficient room on the current page for
  5193.                   the formatted record, the page is advanced by
  5194.                   writing a form feed, a special top-of-page format is
  5195.                   used to format the new page header, and then the
  5196.                   record is written.  By default the top-of-page
  5197.                   format is the name of the filehandle with "_TOP"
  5198.                   appended, but it may be dynamicallly set to the
  5199.                   format of your choice by assigning the name to the
  5200.                   $^ variable while the filehandle is selected.  The
  5201.                   number of lines remaining on the current page is in
  5202.                   variable $-, which can be set to 0 to force a new
  5203.                   page.
  5204.  
  5205.                   If FILEHANDLE is unspecified, output goes to the
  5206.                   current default output channel, which starts out as
  5207.                   STDOUT but may be changed by the select operator.
  5208.  
  5209.  
  5210.  
  5211.      Page 79                                         (printed 1/17/94)
  5212.  
  5213.  
  5214.  
  5215.  
  5216.  
  5217.  
  5218.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5219.  
  5220.  
  5221.  
  5222.                   If the FILEHANDLE is an EXPR, then the expression is
  5223.                   evaluated and the resulting string is used to look
  5224.                   up the name of the FILEHANDLE at run time.  For more
  5225.                   on formats, see the section on formats later on.
  5226.  
  5227.                   Note that write is NOT the opposite of read.
  5228.  
  5229.           PPPPrrrreeeecccceeeeddddeeeennnncccceeee
  5230.  
  5231.           Perl operators have the following associativity and
  5232.           precedence:
  5233.  
  5234.           nonassoc  print printf exec system sort reverse
  5235.                          chmod chown kill unlink utime die return
  5236.           left      ,
  5237.           right     = += -= *= etc.
  5238.           right     ?:
  5239.           nonassoc  ..
  5240.           left      ||
  5241.           left      &&
  5242.           left      | ^
  5243.           left      &
  5244.           nonassoc  == != <=> eq ne cmp
  5245.           nonassoc  < > <= >= lt gt le ge
  5246.           nonassoc  chdir exit eval reset sleep rand umask
  5247.           nonassoc  -r -w -x etc.
  5248.           left      << >>
  5249.           left      + - .
  5250.           left      * / % x
  5251.           left      =~ !~
  5252.           right     ! ~ and unary minus
  5253.           right     **
  5254.           nonassoc  ++ --
  5255.           left      '('
  5256.  
  5257.           As mentioned earlier, if any list operator (print, etc.) or
  5258.           any unary operator (chdir, etc.)  is followed by a left
  5259.           parenthesis as the next token on the same line, the operator
  5260.           and arguments within parentheses are taken to be of highest
  5261.           precedence, just like a normal function call.  Examples:
  5262.  
  5263.                chdir $foo || die;       # (chdir $foo) || die
  5264.                chdir($foo) || die;      # (chdir $foo) || die
  5265.                chdir ($foo) || die;     # (chdir $foo) || die
  5266.                chdir +($foo) || die;    # (chdir $foo) || die
  5267.  
  5268.           but, because * is higher precedence than ||:
  5269.  
  5270.                chdir $foo * 20;         # chdir ($foo * 20)
  5271.                chdir($foo) * 20;        # (chdir $foo) * 20
  5272.                chdir ($foo) * 20;       # (chdir $foo) * 20
  5273.                chdir +($foo) * 20;      # chdir ($foo * 20)
  5274.  
  5275.  
  5276.  
  5277.      Page 80                                         (printed 1/17/94)
  5278.  
  5279.  
  5280.  
  5281.  
  5282.  
  5283.  
  5284.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5285.  
  5286.  
  5287.  
  5288.                rand 10 * 20;            # rand (10 * 20)
  5289.                rand(10) * 20;           # (rand 10) * 20
  5290.                rand (10) * 20;          # (rand 10) * 20
  5291.                rand +(10) * 20;         # rand (10 * 20)
  5292.  
  5293.           In the absence of parentheses, the precedence of list
  5294.           operators such as print, sort or chmod is either very high
  5295.           or very low depending on whether you look at the left side
  5296.           of operator or the right side of it.  For example, in
  5297.  
  5298.                @ary = (1, 3, sort 4, 2);
  5299.                print @ary;         # prints 1324
  5300.  
  5301.           the commas on the right of the sort are evaluated before the
  5302.           sort, but the commas on the left are evaluated after.  In
  5303.           other words, list operators tend to gobble up all the
  5304.           arguments that follow them, and then act like a simple term
  5305.           with regard to the preceding expression.  Note that you have
  5306.           to be careful with parens:
  5307.  
  5308.                # These evaluate exit before doing the print:
  5309.                print($foo, exit);  # Obviously not what you want.
  5310.                print $foo, exit;   # Nor is this.
  5311.  
  5312.                # These do the print before evaluating exit:
  5313.                (print $foo), exit; # This is what you want.
  5314.                print($foo), exit;  # Or this.
  5315.                print ($foo), exit; # Or even this.
  5316.  
  5317.           Also note that
  5318.  
  5319.                print ($foo & 255) + 1, "\n";
  5320.  
  5321.           probably doesn't do what you expect at first glance.
  5322.  
  5323.           SSSSuuuubbbbrrrroooouuuuttttiiiinnnneeeessss
  5324.  
  5325.           A subroutine may be declared as follows:
  5326.  
  5327.               sub NAME BLOCK
  5328.  
  5329.  
  5330.           Any arguments passed to the routine come in as array @_,
  5331.           that is ($_[0], $_[1], ...).  The array @_ is a local array,
  5332.           but its values are references to the actual scalar
  5333.           parameters.  The return value of the subroutine is the value
  5334.           of the last expression evaluated, and can be either an array
  5335.           value or a scalar value.  Alternately, a return statement
  5336.           may be used to specify the returned value and exit the
  5337.           subroutine.  To create local variables see the local
  5338.           operator.
  5339.  
  5340.  
  5341.  
  5342.  
  5343.      Page 81                                         (printed 1/17/94)
  5344.  
  5345.  
  5346.  
  5347.  
  5348.  
  5349.  
  5350.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5351.  
  5352.  
  5353.  
  5354.           A subroutine is called using the do operator or the &
  5355.           operator.
  5356.  
  5357.           Example:
  5358.  
  5359.                sub MAX {
  5360.                     local($max) = pop(@_);
  5361.                     foreach $foo (@_) {
  5362.                          $max = $foo if $max < $foo;
  5363.                     }
  5364.                     $max;
  5365.                }
  5366.  
  5367.                ...
  5368.                $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  5369.  
  5370.           Example:
  5371.  
  5372.                # get a line, combining continuation lines
  5373.                #  that start with whitespace
  5374.                sub get_line {
  5375.                     $thisline = $lookahead;
  5376.                     line: while ($lookahead = <STDIN>) {
  5377.                          if ($lookahead =~ /^[ \t]/) {
  5378.                               $thisline .= $lookahead;
  5379.                          }
  5380.                          else {
  5381.                               last line;
  5382.                          }
  5383.                     }
  5384.                     $thisline;
  5385.                }
  5386.  
  5387.                $lookahead = <STDIN>;    # get first line
  5388.                while ($_ = do get_line()) {
  5389.                     ...
  5390.                }
  5391.  
  5392.           Use array assignment to a local list to name your formal arguments:
  5393.  
  5394.                sub maybeset {
  5395.                     local($key, $value) = @_;
  5396.                     $foo{$key} = $value unless $foo{$key};
  5397.                }
  5398.  
  5399.           This also has the effect of turning call-by-reference into
  5400.           call-by-value, since the assignment copies the values.
  5401.  
  5402.           Subroutines may be called recursively.  If a subroutine is
  5403.           called using the & form, the argument list is optional.  If
  5404.           omitted, no @_ array is set up for the subroutine; the @_
  5405.           array at the time of the call is visible to subroutine
  5406.  
  5407.  
  5408.  
  5409.      Page 82                                         (printed 1/17/94)
  5410.  
  5411.  
  5412.  
  5413.  
  5414.  
  5415.  
  5416.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5417.  
  5418.  
  5419.  
  5420.           instead.
  5421.  
  5422.                do foo(1,2,3);      # pass three arguments
  5423.                &foo(1,2,3);        # the same
  5424.  
  5425.                do foo();      # pass a null list
  5426.                &foo();             # the same
  5427.                &foo;               # pass no arguments--more efficient
  5428.  
  5429.  
  5430.           PPPPaaaassssssssiiiinnnngggg BBBByyyy RRRReeeeffffeeeerrrreeeennnncccceeee
  5431.  
  5432.           Sometimes you don't want to pass the value of an array to a
  5433.           subroutine but rather the name of it, so that the subroutine
  5434.           can modify the global copy of it rather than working with a
  5435.           local copy.  In perl you can refer to all the objects of a
  5436.           particular name by prefixing the name with a star: *foo.
  5437.           When evaluated, it produces a scalar value that represents
  5438.           all the objects of that name, including any filehandle,
  5439.           format or subroutine.  When assigned to within a local()
  5440.           operation, it causes the name mentioned to refer to whatever
  5441.           * value was assigned to it.  Example:
  5442.  
  5443.                sub doubleary {
  5444.                    local(*someary) = @_;
  5445.                    foreach $elem (@someary) {
  5446.                     $elem *= 2;
  5447.                    }
  5448.                }
  5449.                do doubleary(*foo);
  5450.                do doubleary(*bar);
  5451.  
  5452.           Assignment to *name is currently recommended only inside a
  5453.           local().  You can actually assign to *name anywhere, but the
  5454.           previous referent of *name may be stranded forever.  This
  5455.           may or may not bother you.
  5456.  
  5457.           Note that scalars are already passed by reference, so you
  5458.           can modify scalar arguments without using this mechanism by
  5459.           referring explicitly to the $_[nnn] in question.  You can
  5460.           modify all the elements of an array by passing all the
  5461.           elements as scalars, but you have to use the * mechanism to
  5462.           push, pop or change the size of an array.  The * mechanism
  5463.           will probably be more efficient in any case.
  5464.  
  5465.           Since a *name value contains unprintable binary data, if it
  5466.           is used as an argument in a print, or as a %s argument in a
  5467.           printf or sprintf, it then has the value '*name', just so it
  5468.           prints out pretty.
  5469.  
  5470.           Even if you don't want to modify an array, this mechanism is
  5471.           useful for passing multiple arrays in a single LIST, since
  5472.  
  5473.  
  5474.  
  5475.      Page 83                                         (printed 1/17/94)
  5476.  
  5477.  
  5478.  
  5479.  
  5480.  
  5481.  
  5482.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5483.  
  5484.  
  5485.  
  5486.           normally the LIST mechanism will merge all the array values
  5487.           so that you can't extract out the individual arrays.
  5488.  
  5489.           RRRReeeegggguuuullllaaaarrrr EEEExxxxpppprrrreeeessssssssiiiioooonnnnssss
  5490.  
  5491.           The patterns used in pattern matching are regular
  5492.           expressions such as those supplied in the Version 8 regexp
  5493.           routines.  (In fact, the routines are derived from Henry
  5494.           Spencer's freely redistributable reimplementation of the V8
  5495.           routines.)  In addition, \w matches an alphanumeric
  5496.           character (including "_") and \W a nonalphanumeric.  Word
  5497.           boundaries may be matched by \b, and non-boundaries by \B.
  5498.           A whitespace character is matched by \s, non-whitespace by
  5499.           \S.  A numeric character is matched by \d, non-numeric by
  5500.           \D.  You may use \w, \s and \d within character classes.
  5501.           Also, \n, \r, \f, \t and \NNN have their normal
  5502.           interpretations.  Within character classes \b represents
  5503.           backspace rather than a word boundary.  Alternatives may be
  5504.           separated by |.  The bracketing construct ( ... ) may also
  5505.           be used, in which case \<digit> matches the digit'th
  5506.           substring.  (Outside of the pattern, always use $ instead of
  5507.           \ in front of the digit.  The scope of $<digit> (and $`, $&
  5508.           and $') extends to the end of the enclosing BLOCK or eval
  5509.           string, or to the next pattern match with subexpressions.
  5510.           The \<digit> notation sometimes works outside the current
  5511.           pattern, but should not be relied upon.)  You may have as
  5512.           many parentheses as you wish.  If you have more than 9
  5513.           substrings, the variables $10, $11, ... refer to the
  5514.           corresponding substring.  Within the pattern, \10, \11, etc.
  5515.           refer back to substrings if there have been at least that
  5516.           many left parens before the backreference.  Otherwise (for
  5517.           backward compatibilty) \10 is the same as \010, a backspace,
  5518.           and \11 the same as \011, a tab.  And so on.  (\1 through \9
  5519.           are always backreferences.)
  5520.  
  5521.           $+ returns whatever the last bracket match matched.  $&
  5522.           returns the entire matched string.  ($0 used to return the
  5523.           same thing, but not any more.)  $` returns everything before
  5524.           the matched string.  $' returns everything after the matched
  5525.           string.  Examples:
  5526.  
  5527.                s/^([^ ]*) *([^ ]*)/$2 $1/;   # swap first two words
  5528.  
  5529.                if (/Time: (..):(..):(..)/) {
  5530.                     $hours = $1;
  5531.                     $minutes = $2;
  5532.                     $seconds = $3;
  5533.                }
  5534.  
  5535.           By default, the ^ character is only guaranteed to match at
  5536.           the beginning of the string, the $ character only at the end
  5537.           (or before the newline at the end) and perl does certain
  5538.  
  5539.  
  5540.  
  5541.      Page 84                                         (printed 1/17/94)
  5542.  
  5543.  
  5544.  
  5545.  
  5546.  
  5547.  
  5548.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5549.  
  5550.  
  5551.  
  5552.           optimizations with the assumption that the string contains
  5553.           only one line.  The behavior of ^ and $ on embedded newlines
  5554.           will be inconsistent.  You may, however, wish to treat a
  5555.           string as a multi-line buffer, such that the ^ will match
  5556.           after any newline within the string, and $ will match before
  5557.           any newline.  At the cost of a little more overhead, you can
  5558.           do this by setting the variable $* to 1.  Setting it back to
  5559.           0 makes perl revert to its old behavior.
  5560.  
  5561.           To facilitate multi-line substitutions, the . character
  5562.           never matches a newline (even when $* is 0).  In particular,
  5563.           the following leaves a newline on the $_ string:
  5564.  
  5565.                $_ = <STDIN>;
  5566.                s/.*(some_string).*/$1/;
  5567.  
  5568.           If the newline is unwanted, try one of
  5569.  
  5570.                s/.*(some_string).*\n/$1/;
  5571.                s/.*(some_string)[^\000]*/$1/;
  5572.                s/.*(some_string)(.|\n)*/$1/;
  5573.                chop; s/.*(some_string).*/$1/;
  5574.                /(some_string)/ && ($_ = $1);
  5575.  
  5576.           Any item of a regular expression may be followed with digits
  5577.           in curly brackets of the form {n,m}, where n gives the
  5578.           minimum number of times to match the item and m gives the
  5579.           maximum.  The form {n} is equivalent to {n,n} and matches
  5580.           exactly n times.  The form {n,} matches n or more times.
  5581.           (If a curly bracket occurs in any other context, it is
  5582.           treated as a regular character.)  The * modifier is
  5583.           equivalent to {0,}, the + modifier to {1,} and the ?
  5584.           modifier to {0,1}.  There is no limit to the size of n or m,
  5585.           but large numbers will chew up more memory.
  5586.  
  5587.           You will note that all backslashed metacharacters in perl
  5588.           are alphanumeric, such as \b, \w, \n.  Unlike some other
  5589.           regular expression languages, there are no backslashed
  5590.           symbols that aren't alphanumeric.  So anything that looks
  5591.           like \\, \(, \), \<, \>, \{, or \} is always interpreted as
  5592.           a literal character, not a metacharacter.  This makes it
  5593.           simple to quote a string that you want to use for a pattern
  5594.           but that you are afraid might contain metacharacters.
  5595.           Simply quote all the non-alphanumeric characters:
  5596.  
  5597.                $pattern =~ s/(\W)/\\$1/g;
  5598.  
  5599.  
  5600.           FFFFoooorrrrmmmmaaaattttssss
  5601.  
  5602.           Output record formats for use with the write operator may
  5603.           declared as follows:
  5604.  
  5605.  
  5606.  
  5607.      Page 85                                         (printed 1/17/94)
  5608.  
  5609.  
  5610.  
  5611.  
  5612.  
  5613.  
  5614.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5615.  
  5616.  
  5617.  
  5618.               format NAME =
  5619.               FORMLIST
  5620.               .
  5621.  
  5622.           If name is omitted, format "STDOUT" is defined.  FORMLIST
  5623.           consists of a sequence of lines, each of which may be of one
  5624.           of three types:
  5625.  
  5626.           1.  A comment.
  5627.  
  5628.           2.  A "picture" line giving the format for one output line.
  5629.  
  5630.           3.  An argument line supplying values to plug into a picture
  5631.               line.
  5632.  
  5633.           Picture lines are printed exactly as they look, except for
  5634.           certain fields that substitute values into the line.  Each
  5635.           picture field starts with either @ or ^.  The @ field (not
  5636.           to be confused with the array marker @) is the normal case;
  5637.           ^ fields are used to do rudimentary multi-line text block
  5638.           filling.  The length of the field is supplied by padding out
  5639.           the field with multiple <, >, or | characters to specify,
  5640.           respectively, left justification, right justification, or
  5641.           centering.  As an alternate form of right justification, you
  5642.           may also use # characters (with an optional .) to specify a
  5643.           numeric field.  (Use of ^ instead of @ causes the field to
  5644.           be blanked if undefined.)  If any of the values supplied for
  5645.           these fields contains a newline, only the text up to the
  5646.           newline is printed.  The special field @* can be used for
  5647.           printing multi-line values.  It should appear by itself on a
  5648.           line.
  5649.  
  5650.           The values are specified on the following line, in the same
  5651.           order as the picture fields.  The values should be separated
  5652.           by commas.
  5653.  
  5654.           Picture fields that begin with ^ rather than @ are treated
  5655.           specially.  The value supplied must be a scalar variable
  5656.           name which contains a text string.  Perl puts as much text
  5657.           as it can into the field, and then chops off the front of
  5658.           the string so that the next time the variable is referenced,
  5659.           more of the text can be printed.  Normally you would use a
  5660.           sequence of fields in a vertical stack to print out a block
  5661.           of text.  If you like, you can end the final field with ...,
  5662.           which will appear in the output if the text was too long to
  5663.           appear in its entirety.  You can change which characters are
  5664.           legal to break on by changing the variable $: to a list of
  5665.           the desired characters.
  5666.  
  5667.           Since use of ^ fields can produce variable length records if
  5668.           the text to be formatted is short, you can suppress blank
  5669.           lines by putting the tilde (~) character anywhere in the
  5670.  
  5671.  
  5672.  
  5673.      Page 86                                         (printed 1/17/94)
  5674.  
  5675.  
  5676.  
  5677.  
  5678.  
  5679.  
  5680.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5681.  
  5682.  
  5683.  
  5684.           line.  (Normally you should put it in the front if possible,
  5685.           for visibility.)  The tilde will be translated to a space
  5686.           upon output.  If you put a second tilde contiguous to the
  5687.           first, the line will be repeated until all the fields on the
  5688.           line are exhausted.  (If you use a field of the @ variety,
  5689.           the expression you supply had better not give the same value
  5690.           every time forever!)
  5691.  
  5692.           Examples:
  5693.  
  5694.           # a report on the /etc/passwd file
  5695.           format STDOUT_TOP =
  5696.                                   Passwd File
  5697.           Name                Login    Office   Uid   Gid Home
  5698.           ------------------------------------------------------------------
  5699.           .
  5700.           format STDOUT =
  5701.           @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  5702.           $name,              $login,  $office,$uid,$gid, $home
  5703.           .
  5704.  
  5705.           # a report from a bug report form
  5706.           format STDOUT_TOP =
  5707.                                   Bug Reports
  5708.           @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  5709.           $system,                      $%,         $date
  5710.           ------------------------------------------------------------------
  5711.           .
  5712.           format STDOUT =
  5713.           Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5714.                    $subject
  5715.           Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5716.                  $index,                       $description
  5717.           Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5718.                     $priority,        $date,   $description
  5719.           From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5720.                 $from,                         $description
  5721.           Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5722.                        $programmer,            $description
  5723.           ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5724.                                                $description
  5725.           ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5726.                                                $description
  5727.           ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5728.                                                $description
  5729.           ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5730.                                                $description
  5731.           ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  5732.                                                $description
  5733.           .
  5734.  
  5735.           It is possible to intermix prints with writes on the same
  5736.  
  5737.  
  5738.  
  5739.      Page 87                                         (printed 1/17/94)
  5740.  
  5741.  
  5742.  
  5743.  
  5744.  
  5745.  
  5746.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5747.  
  5748.  
  5749.  
  5750.           output channel, but you'll have to handle $- (lines left on
  5751.           the page) yourself.
  5752.  
  5753.           If you are printing lots of fields that are usually blank,
  5754.           you should consider using the reset operator between
  5755.           records.  Not only is it more efficient, but it can prevent
  5756.           the bug of adding another field and forgetting to zero it.
  5757.  
  5758.           IIIInnnntttteeeerrrrpppprrrroooocccceeeessssssss CCCCoooommmmmmmmuuuunnnniiiiccccaaaattttiiiioooonnnn
  5759.  
  5760.           The IPC facilities of perl are built on the Berkeley socket
  5761.           mechanism.  If you don't have sockets, you can ignore this
  5762.           section.  The calls have the same names as the corresponding
  5763.           system calls, but the arguments tend to differ, for two
  5764.           reasons.  First, perl file handles work differently than C
  5765.           file descriptors.  Second, perl already knows the length of
  5766.           its strings, so you don't need to pass that information.
  5767.           Here is a sample client (untested):
  5768.  
  5769.                ($them,$port) = @ARGV;
  5770.                $port = 2345 unless $port;
  5771.                $them = 'localhost' unless $them;
  5772.  
  5773.                $SIG{'INT'} = 'dokill';
  5774.                sub dokill { kill 9,$child if $child; }
  5775.  
  5776.                require 'sys/socket.ph';
  5777.  
  5778.                $sockaddr = 'S n a4 x8';
  5779.                chop($hostname = `hostname`);
  5780.  
  5781.                ($name, $aliases, $proto) = getprotobyname('tcp');
  5782.                ($name, $aliases, $port) = getservbyname($port, 'tcp')
  5783.                     unless $port =~ /^\d+$/;
  5784.                ($name, $aliases, $type, $len, $thisaddr) =
  5785.                                    gethostbyname($hostname);
  5786.                ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  5787.  
  5788.                $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  5789.                $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  5790.  
  5791.                socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  5792.                bind(S, $this) || die "bind: $!";
  5793.                connect(S, $that) || die "connect: $!";
  5794.  
  5795.                select(S); $| = 1; select(stdout);
  5796.  
  5797.                if ($child = fork) {
  5798.                     while (<>) {
  5799.                          print S;
  5800.                     }
  5801.                     sleep 3;
  5802.  
  5803.  
  5804.  
  5805.      Page 88                                         (printed 1/17/94)
  5806.  
  5807.  
  5808.  
  5809.  
  5810.  
  5811.  
  5812.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5813.  
  5814.  
  5815.  
  5816.                     do dokill();
  5817.                }
  5818.                else {
  5819.                     while (<S>) {
  5820.                          print;
  5821.                     }
  5822.                }
  5823.  
  5824.           And here's a server:
  5825.  
  5826.                ($port) = @ARGV;
  5827.                $port = 2345 unless $port;
  5828.  
  5829.                require 'sys/socket.ph';
  5830.  
  5831.                $sockaddr = 'S n a4 x8';
  5832.  
  5833.                ($name, $aliases, $proto) = getprotobyname('tcp');
  5834.                ($name, $aliases, $port) = getservbyname($port, 'tcp')
  5835.                     unless $port =~ /^\d+$/;
  5836.  
  5837.                $this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
  5838.  
  5839.                select(NS); $| = 1; select(stdout);
  5840.  
  5841.                socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  5842.                bind(S, $this) || die "bind: $!";
  5843.                listen(S, 5) || die "connect: $!";
  5844.  
  5845.                select(S); $| = 1; select(stdout);
  5846.  
  5847.                for (;;) {
  5848.                     print "Listening again\n";
  5849.                     ($addr = accept(NS,S)) || die $!;
  5850.                     print "accept ok\n";
  5851.  
  5852.                     ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  5853.                     @inetaddr = unpack('C4',$inetaddr);
  5854.                     print "$af $port @inetaddr\n";
  5855.  
  5856.                     while (<NS>) {
  5857.                          print;
  5858.                          print NS;
  5859.                     }
  5860.                }
  5861.  
  5862.  
  5863.           PPPPrrrreeeeddddeeeeffffiiiinnnneeeedddd NNNNaaaammmmeeeessss
  5864.  
  5865.           The following names have special meaning to perl.  I could
  5866.           have used alphabetic symbols for some of these, but I didn't
  5867.           want to take the chance that someone would say reset
  5868.  
  5869.  
  5870.  
  5871.      Page 89                                         (printed 1/17/94)
  5872.  
  5873.  
  5874.  
  5875.  
  5876.  
  5877.  
  5878.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5879.  
  5880.  
  5881.  
  5882.           "a-zA-Z" and wipe them all out.  You'll just have to suffer
  5883.           along with these silly symbols.  Most of them have
  5884.           reasonable mnemonics, or analogues in one of the shells.
  5885.  
  5886.           $_      The default input and pattern-searching space.  The
  5887.                   following pairs are equivalent:
  5888.  
  5889.                        while (<>) {...     # only equivalent in while!
  5890.                        while ($_ = <>) {...
  5891.  
  5892.                        /^Subject:/
  5893.                        $_ =~ /^Subject:/
  5894.  
  5895.                        y/a-z/A-Z/
  5896.                        $_ =~ y/a-z/A-Z/
  5897.  
  5898.                        chop
  5899.                        chop($_)
  5900.  
  5901.                   (Mnemonic: underline is understood in certain
  5902.                   operations.)
  5903.  
  5904.           $.      The current input line number of the last filehandle
  5905.                   that was read.  Readonly.  Remember that only an
  5906.                   explicit close on the filehandle resets the line
  5907.                   number.  Since <> never does an explicit close, line
  5908.                   numbers increase across ARGV files (but see examples
  5909.                   under eof).  (Mnemonic: many programs use . to mean
  5910.                   the current line number.)
  5911.  
  5912.           $/      The input record separator, newline by default.
  5913.                   Works like awk's RS variable, including treating
  5914.                   blank lines as delimiters if set to the null string.
  5915.                   You may set it to a multicharacter string to match a
  5916.                   multi-character delimiter.  Note that setting it to
  5917.                   "\n\n" means something slightly different than
  5918.                   setting it to "", if the file contains consecutive
  5919.                   blank lines.  Setting it to "" will treat two or
  5920.                   more consecutive blank lines as a single blank line.
  5921.                   Setting it to "\n\n" will blindly assume that the
  5922.                   next input character belongs to the next paragraph,
  5923.                   even if it's a newline.  (Mnemonic: / is used to
  5924.                   delimit line boundaries when quoting poetry.)
  5925.  
  5926.           $,      The output field separator for the print operator.
  5927.                   Ordinarily the print operator simply prints out the
  5928.                   comma separated fields you specify.  In order to get
  5929.                   behavior more like awk, set this variable as you
  5930.                   would set awk's OFS variable to specify what is
  5931.                   printed between fields.  (Mnemonic: what is printed
  5932.                   when there is a , in your print statement.)
  5933.  
  5934.  
  5935.  
  5936.  
  5937.      Page 90                                         (printed 1/17/94)
  5938.  
  5939.  
  5940.  
  5941.  
  5942.  
  5943.  
  5944.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  5945.  
  5946.  
  5947.  
  5948.           $"      This is like $, except that it applies to array
  5949.                   values interpolated into a double-quoted string (or
  5950.                   similar interpreted string).  Default is a space.
  5951.                   (Mnemonic: obvious, I think.)
  5952.  
  5953.           $\      The output record separator for the print operator.
  5954.                   Ordinarily the print operator simply prints out the
  5955.                   comma separated fields you specify, with no trailing
  5956.                   newline or record separator assumed.  In order to
  5957.                   get behavior more like awk, set this variable as you
  5958.                   would set awk's ORS variable to specify what is
  5959.                   printed at the end of the print.  (Mnemonic: you set
  5960.                   $\ instead of adding \n at the end of the print.
  5961.                   Also, it's just like /, but it's what you get "back"
  5962.                   from perl.)
  5963.  
  5964.           $#      The output format for printed numbers.  This
  5965.                   variable is a half-hearted attempt to emulate awk's
  5966.                   OFMT variable.  There are times, however, when awk
  5967.                   and perl have differing notions of what is in fact
  5968.                   numeric.  Also, the initial value is %.20g rather
  5969.                   than %.6g, so you need to set $# explicitly to get
  5970.                   awk's value.  (Mnemonic: # is the number sign.)
  5971.  
  5972.           $%      The current page number of the currently selected
  5973.                   output channel.  (Mnemonic: % is page number in
  5974.                   nroff.)
  5975.  
  5976.           $=      The current page length (printable lines) of the
  5977.                   currently selected output channel.  Default is 60.
  5978.                   (Mnemonic: = has horizontal lines.)
  5979.  
  5980.           $-      The number of lines left on the page of the
  5981.                   currently selected output channel.  (Mnemonic:
  5982.                   lines_on_page - lines_printed.)
  5983.  
  5984.           $~      The name of the current report format for the
  5985.                   currently selected output channel.  Default is name
  5986.                   of the filehandle.  (Mnemonic: brother to $^.)
  5987.  
  5988.           $^      The name of the current top-of-page format for the
  5989.                   currently selected output channel.  Default is name
  5990.                   of the filehandle with "_TOP" appended.  (Mnemonic:
  5991.                   points to top of page.)
  5992.  
  5993.           $|      If set to nonzero, forces a flush after every write
  5994.                   or print on the currently selected output channel.
  5995.                   Default is 0.  Note that STDOUT will typically be
  5996.                   line buffered if output is to the terminal and block
  5997.                   buffered otherwise.  Setting this variable is useful
  5998.                   primarily when you are outputting to a pipe, such as
  5999.                   when you are running a perl script under rsh and
  6000.  
  6001.  
  6002.  
  6003.      Page 91                                         (printed 1/17/94)
  6004.  
  6005.  
  6006.  
  6007.  
  6008.  
  6009.  
  6010.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6011.  
  6012.  
  6013.  
  6014.                   want to see the output as it's happening.
  6015.                   (Mnemonic: when you want your pipes to be piping
  6016.                   hot.)
  6017.  
  6018.           $$      The process number of the perl running this script.
  6019.                   (Mnemonic: same as shells.)
  6020.  
  6021.           $?      The status returned by the last pipe close, backtick
  6022.                   (``) command or system operator.  Note that this is
  6023.                   the status word returned by the wait() system call,
  6024.                   so the exit value of the subprocess is actually ($?
  6025.                   >> 8).  $? & 255 gives which signal, if any, the
  6026.                   process died from, and whether there was a core
  6027.                   dump.  (Mnemonic: similar to sh and ksh.)
  6028.  
  6029.           $&      The string matched by the last successful pattern
  6030.                   match (not counting any matches hidden within a
  6031.                   BLOCK or eval enclosed by the current BLOCK).
  6032.                   (Mnemonic: like & in some editors.)
  6033.  
  6034.           $`      The string preceding whatever was matched by the
  6035.                   last successful pattern match (not counting any
  6036.                   matches hidden within a BLOCK or eval enclosed by
  6037.                   the current BLOCK).  (Mnemonic: ` often precedes a
  6038.                   quoted string.)
  6039.  
  6040.           $'      The string following whatever was matched by the
  6041.                   last successful pattern match (not counting any
  6042.                   matches hidden within a BLOCK or eval enclosed by
  6043.                   the current BLOCK).  (Mnemonic: ' often follows a
  6044.                   quoted string.)  Example:
  6045.  
  6046.                        $_ = 'abcdefghi';
  6047.                        /def/;
  6048.                        print "$`:$&:$'\n";      # prints abc:def:ghi
  6049.  
  6050.  
  6051.           $+      The last bracket matched by the last search pattern.
  6052.                   This is useful if you don't know which of a set of
  6053.                   alternative patterns matched.  For example:
  6054.  
  6055.                       /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  6056.  
  6057.                   (Mnemonic: be positive and forward looking.)
  6058.  
  6059.           $*      Set to 1 to do multiline matching within a string, 0
  6060.                   to tell perl that it can assume that strings contain
  6061.                   a single line, for the purpose of optimizing pattern
  6062.                   matches.  Pattern matches on strings containing
  6063.                   multiple newlines can produce confusing results when
  6064.                   $* is 0.  Default is 0.  (Mnemonic: * matches
  6065.                   multiple things.)  Note that this variable only
  6066.  
  6067.  
  6068.  
  6069.      Page 92                                         (printed 1/17/94)
  6070.  
  6071.  
  6072.  
  6073.  
  6074.  
  6075.  
  6076.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6077.  
  6078.  
  6079.  
  6080.                   influences the interpretation of ^ and $.  A literal
  6081.                   newline can be searched for even when $* == 0.
  6082.  
  6083.           $0      Contains the name of the file containing the perl
  6084.                   script being executed.  Assigning to $0 modifies the
  6085.                   argument area that the ps(1) program sees.
  6086.                   (Mnemonic: same as sh and ksh.)
  6087.  
  6088.           $<digit>
  6089.                   Contains the subpattern from the corresponding set
  6090.                   of parentheses in the last pattern matched, not
  6091.                   counting patterns matched in nested blocks that have
  6092.                   been exited already.  (Mnemonic: like \digit.)
  6093.  
  6094.           $[      The index of the first element in an array, and of
  6095.                   the first character in a substring.  Default is 0,
  6096.                   but you could set it to 1 to make perl behave more
  6097.                   like awk (or Fortran) when subscripting and when
  6098.                   evaluating the index() and substr() functions.
  6099.                   (Mnemonic: [ begins subscripts.)
  6100.  
  6101.           $]      The string printed out when you say "perl -v".  It
  6102.                   can be used to determine at the beginning of a
  6103.                   script whether the perl interpreter executing the
  6104.                   script is in the right range of versions.  If used
  6105.                   in a numeric context, returns the version +
  6106.                   patchlevel / 1000.  Example:
  6107.  
  6108.                        # see if getc is available
  6109.                           ($version,$patchlevel) =
  6110.                              $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  6111.                           print STDERR "(No filename completion available.)\n"
  6112.                              if $version * 1000 + $patchlevel < 2016;
  6113.  
  6114.                   or, used numerically,
  6115.  
  6116.                        warn "No checksumming!\n" if $] < 3.019;
  6117.  
  6118.                   (Mnemonic: Is this version of perl in the right
  6119.                   bracket?)
  6120.  
  6121.           $;      The subscript separator for multi-dimensional array
  6122.                   emulation.  If you refer to an associative array
  6123.                   element as
  6124.                        $foo{$a,$b,$c}
  6125.  
  6126.                   it really means
  6127.  
  6128.                        $foo{join($;, $a, $b, $c)}
  6129.  
  6130.                   But don't put
  6131.  
  6132.  
  6133.  
  6134.  
  6135.      Page 93                                         (printed 1/17/94)
  6136.  
  6137.  
  6138.  
  6139.  
  6140.  
  6141.  
  6142.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6143.  
  6144.  
  6145.  
  6146.                        @foo{$a,$b,$c}      # a slice--note the @
  6147.  
  6148.                   which means
  6149.  
  6150.                        ($foo{$a},$foo{$b},$foo{$c})
  6151.  
  6152.                   Default is "\034", the same as SUBSEP in awk.  Note
  6153.                   that if your keys contain binary data there might
  6154.                   not be any safe value for $;.  (Mnemonic: comma (the
  6155.                   syntactic subscript separator) is a semi-semicolon.
  6156.                   Yeah, I know, it's pretty lame, but $, is already
  6157.                   taken for something more important.)
  6158.  
  6159.           $!      If used in a numeric context, yields the current
  6160.                   value of errno, with all the usual caveats.  (This
  6161.                   means that you shouldn't depend on the value of $!
  6162.                   to be anything in particular unless you've gotten a
  6163.                   specific error return indicating a system error.)
  6164.                   If used in a string context, yields the
  6165.                   corresponding system error string.  You can assign
  6166.                   to $! in order to set errno if, for instance, you
  6167.                   want $! to return the string for error n, or you
  6168.                   want to set the exit value for the die operator.
  6169.                   (Mnemonic: What just went bang?)
  6170.  
  6171.           $@      The perl syntax error message from the last eval
  6172.                   command.  If null, the last eval parsed and executed
  6173.                   correctly (although the operations you invoked may
  6174.                   have failed in the normal fashion).  (Mnemonic:
  6175.                   Where was the syntax error "at"?)
  6176.  
  6177.           $<      The real uid of this process.  (Mnemonic: it's the
  6178.                   uid you came FROM, if you're running setuid.)
  6179.  
  6180.           $>      The effective uid of this process.  Example:
  6181.  
  6182.                        $< = $>;  # set real uid to the effective uid
  6183.                        ($<,$>) = ($>,$<);  # swap real and effective uid
  6184.  
  6185.                   (Mnemonic: it's the uid you went TO, if you're
  6186.                   running setuid.)  Note: $< and $> can only be
  6187.                   swapped on machines supporting setreuid().
  6188.  
  6189.           $(      The real gid of this process.  If you are on a
  6190.                   machine that supports membership in multiple groups
  6191.                   simultaneously, gives a space separated list of
  6192.                   groups you are in.  The first number is the one
  6193.                   returned by getgid(), and the subsequent ones by
  6194.                   getgroups(), one of which may be the same as the
  6195.                   first number.  (Mnemonic: parentheses are used to
  6196.                   GROUP things.  The real gid is the group you LEFT,
  6197.                   if you're running setgid.)
  6198.  
  6199.  
  6200.  
  6201.      Page 94                                         (printed 1/17/94)
  6202.  
  6203.  
  6204.  
  6205.  
  6206.  
  6207.  
  6208.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6209.  
  6210.  
  6211.  
  6212.           $)      The effective gid of this process.  If you are on a
  6213.                   machine that supports membership in multiple groups
  6214.                   simultaneously, gives a space separated list of
  6215.                   groups you are in.  The first number is the one
  6216.                   returned by getegid(), and the subsequent ones by
  6217.                   getgroups(), one of which may be the same as the
  6218.                   first number.  (Mnemonic: parentheses are used to
  6219.                   GROUP things.  The effective gid is the group that's
  6220.                   RIGHT for you, if you're running setgid.)
  6221.  
  6222.                   Note: $<, $>, $( and $) can only be set on machines
  6223.                   that support the corresponding set[re][ug]id()
  6224.                   routine.  $( and $) can only be swapped on machines
  6225.                   supporting setregid().
  6226.  
  6227.           $:      The current set of characters after which a string
  6228.                   may be broken to fill continuation fields (starting
  6229.                   with ^) in a format.  Default is " \n-", to break on
  6230.                   whitespace or hyphens.  (Mnemonic: a "colon" in
  6231.                   poetry is a part of a line.)
  6232.  
  6233.           $^D     The current value of the debugging flags.
  6234.                   (Mnemonic: value of ----DDDD switch.)
  6235.  
  6236.           $^F     The maximum system file descriptor, ordinarily 2.
  6237.                   System file descriptors are passed to subprocesses,
  6238.                   while higher file descriptors are not.  During an
  6239.                   open, system file descriptors are preserved even if
  6240.                   the open fails.  Ordinary file descriptors are
  6241.                   closed before the open is attempted.
  6242.  
  6243.           $^I     The current value of the inplace-edit extension.
  6244.                   Use undef to disable inplace editing.  (Mnemonic:
  6245.                   value of ----iiii switch.)
  6246.  
  6247.           $^L     What formats output to perform a formfeed.  Default
  6248.                   is \f.
  6249.  
  6250.           $^P     The internal flag that the debugger clears so that
  6251.                   it doesn't debug itself.  You could conceivable
  6252.                   disable debugging yourself by clearing it.
  6253.  
  6254.           $^T     The time at which the script began running, in
  6255.                   seconds since the epoch.  The values returned by the
  6256.                   ----MMMM ,,,, ----AAAA and ----CCCC filetests are based on this value.
  6257.  
  6258.           $^W     The current value of the warning switch.  (Mnemonic:
  6259.                   related to the ----wwww switch.)
  6260.  
  6261.           $^X     The name that Perl itself was executed as, from
  6262.                   argv[0].
  6263.  
  6264.  
  6265.  
  6266.  
  6267.      Page 95                                         (printed 1/17/94)
  6268.  
  6269.  
  6270.  
  6271.  
  6272.  
  6273.  
  6274.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6275.  
  6276.  
  6277.  
  6278.           $ARGV   contains the name of the current file when reading
  6279.                   from <>.
  6280.  
  6281.           @ARGV   The array ARGV contains the command line arguments
  6282.                   intended for the script.  Note that $#ARGV is the
  6283.                   generally number of arguments minus one, since
  6284.                   $ARGV[0] is the first argument, NOT the command
  6285.                   name.  See $0 for the command name.
  6286.  
  6287.           @INC    The array INC contains the list of places to look
  6288.                   for perl scripts to be evaluated by the "do EXPR"
  6289.                   command or the "require" command.  It initially
  6290.                   consists of the arguments to any ----IIII command line
  6291.                   switches, followed by the default perl library,
  6292.                   probably "/usr/local/lib/perl", followed by ".", to
  6293.                   represent the current directory.
  6294.  
  6295.           %INC    The associative array INC contains entries for each
  6296.                   filename that has been included via "do" or
  6297.                   "require".  The key is the filename you specified,
  6298.                   and the value is the location of the file actually
  6299.                   found.  The "require" command uses this array to
  6300.                   determine whether a given file has already been
  6301.                   included.
  6302.  
  6303.           $ENV{expr}
  6304.                   The associative array ENV contains your current
  6305.                   environment.  Setting a value in ENV changes the
  6306.                   environment for child processes.
  6307.  
  6308.           $SIG{expr}
  6309.                   The associative array SIG is used to set signal
  6310.                   handlers for various signals.  Example:
  6311.  
  6312.                        sub handler {  # 1st argument is signal name
  6313.                             local($sig) = @_;
  6314.                             print "Caught a SIG$sig--shutting down\n";
  6315.                             close(LOG);
  6316.                             exit(0);
  6317.                        }
  6318.  
  6319.                        $SIG{'INT'} = 'handler';
  6320.                        $SIG{'QUIT'} = 'handler';
  6321.                        ...
  6322.                        $SIG{'INT'} = 'DEFAULT'; # restore default action
  6323.                        $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
  6324.  
  6325.                   The SIG array only contains values for the signals
  6326.                   actually set within the perl script.
  6327.  
  6328.  
  6329.  
  6330.  
  6331.  
  6332.  
  6333.      Page 96                                         (printed 1/17/94)
  6334.  
  6335.  
  6336.  
  6337.  
  6338.  
  6339.  
  6340.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6341.  
  6342.  
  6343.  
  6344.           PPPPaaaacccckkkkaaaaggggeeeessss
  6345.  
  6346.           Perl provides a mechanism for alternate namespaces to
  6347.           protect packages from stomping on each others variables.  By
  6348.           default, a perl script starts compiling into the package
  6349.           known as "main".  By use of the package declaration, you can
  6350.           switch namespaces.  The scope of the package declaration is
  6351.           from the declaration itself to the end of the enclosing
  6352.           block (the same scope as the local() operator).  Typically
  6353.           it would be the first declaration in a file to be included
  6354.           by the "require" operator.  You can switch into a package in
  6355.           more than one place; it merely influences which symbol table
  6356.           is used by the compiler for the rest of that block.  You can
  6357.           refer to variables and filehandles in other packages by
  6358.           prefixing the identifier with the package name and a single
  6359.           quote.  If the package name is null, the "main" package as
  6360.           assumed.
  6361.  
  6362.           Only identifiers starting with letters are stored in the
  6363.           packages symbol table.  All other symbols are kept in
  6364.           package "main".  In addition, the identifiers STDIN, STDOUT,
  6365.           STDERR, ARGV, ARGVOUT, ENV, INC and SIG are forced to be in
  6366.           package "main", even when used for other purposes than their
  6367.           built-in one.  Note also that, if you have a package called
  6368.           "m", "s" or "y", the you can't use the qualified form of an
  6369.           identifier since it will be interpreted instead as a pattern
  6370.           match, a substitution or a translation.
  6371.  
  6372.           Eval'ed strings are compiled in the package in which the
  6373.           eval was compiled in.  (Assignments to $SIG{}, however,
  6374.           assume the signal handler specified is in the main package.
  6375.           Qualify the signal handler name if you wish to have a signal
  6376.           handler in a package.)  For an example, examine perldb.pl in
  6377.           the perl library.  It initially switches to the DB package
  6378.           so that the debugger doesn't interfere with variables in the
  6379.           script you are trying to debug.  At various points, however,
  6380.           it temporarily switches back to the main package to evaluate
  6381.           various expressions in the context of the main package.
  6382.  
  6383.           The symbol table for a package happens to be stored in the
  6384.           associative array of that name prepended with an underscore.
  6385.           The value in each entry of the associative array is what you
  6386.           are referring to when you use the *name notation.  In fact,
  6387.           the following have the same effect (in package main,
  6388.           anyway), though the first is more efficient because it does
  6389.           the symbol table lookups at compile time:
  6390.  
  6391.                local(*foo) = *bar;
  6392.                local($_main{'foo'}) = $_main{'bar'};
  6393.  
  6394.           You can use this to print out all the variables in a
  6395.           package, for instance.  Here is dumpvar.pl from the perl
  6396.  
  6397.  
  6398.  
  6399.      Page 97                                         (printed 1/17/94)
  6400.  
  6401.  
  6402.  
  6403.  
  6404.  
  6405.  
  6406.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6407.  
  6408.  
  6409.  
  6410.           library:
  6411.                package dumpvar;
  6412.  
  6413.                sub main'dumpvar {
  6414.                    ($package) = @_;
  6415.                    local(*stab) = eval("*_$package");
  6416.                    while (($key,$val) = each(%stab)) {
  6417.                        {
  6418.                            local(*entry) = $val;
  6419.                            if (defined $entry) {
  6420.                                print "\$$key = '$entry'\n";
  6421.                            }
  6422.                            if (defined @entry) {
  6423.                                print "\@$key = (\n";
  6424.                                foreach $num ($[ .. $#entry) {
  6425.                                    print "  $num\t'",$entry[$num],"'\n";
  6426.                                }
  6427.                                print ")\n";
  6428.                            }
  6429.                            if ($key ne "_$package" && defined %entry) {
  6430.                                print "\%$key = (\n";
  6431.                                foreach $key (sort keys(%entry)) {
  6432.                                    print "  $key\t'",$entry{$key},"'\n";
  6433.                                }
  6434.                                print ")\n";
  6435.                            }
  6436.                        }
  6437.                    }
  6438.                }
  6439.  
  6440.           Note that, even though the subroutine is compiled in package
  6441.           dumpvar, the name of the subroutine is qualified so that its
  6442.           name is inserted into package "main".
  6443.  
  6444.           SSSSttttyyyylllleeee
  6445.  
  6446.           Each programmer will, of course, have his or her own
  6447.           preferences in regards to formatting, but there are some
  6448.           general guidelines that will make your programs easier to
  6449.           read.
  6450.  
  6451.           1.  Just because you CAN do something a particular way
  6452.               doesn't mean that you SHOULD do it that way.  Perl is
  6453.               designed to give you several ways to do anything, so
  6454.               consider picking the most readable one.  For instance
  6455.  
  6456.                    open(FOO,$foo) || die "Can't open $foo: $!";
  6457.  
  6458.               is better than
  6459.  
  6460.                    die "Can't open $foo: $!" unless open(FOO,$foo);
  6461.  
  6462.  
  6463.  
  6464.  
  6465.      Page 98                                         (printed 1/17/94)
  6466.  
  6467.  
  6468.  
  6469.  
  6470.  
  6471.  
  6472.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6473.  
  6474.  
  6475.  
  6476.               because the second way hides the main point of the
  6477.               statement in a modifier.  On the other hand
  6478.  
  6479.                    print "Starting analysis\n" if $verbose;
  6480.  
  6481.               is better than
  6482.  
  6483.                    $verbose && print "Starting analysis\n";
  6484.  
  6485.               since the main point isn't whether the user typed -v or
  6486.               not.
  6487.  
  6488.               Similarly, just because an operator lets you assume
  6489.               default arguments doesn't mean that you have to make use
  6490.               of the defaults.  The defaults are there for lazy
  6491.               systems programmers writing one-shot programs.  If you
  6492.               want your program to be readable, consider supplying the
  6493.               argument.
  6494.  
  6495.               Along the same lines, just because you can omit
  6496.               parentheses in many places doesn't mean that you ought
  6497.               to:
  6498.  
  6499.                    return print reverse sort num values array;
  6500.                    return print(reverse(sort num (values(%array))));
  6501.  
  6502.               When in doubt, parenthesize.  At the very least it will
  6503.               let some poor schmuck bounce on the % key in vi.
  6504.  
  6505.               Even if you aren't in doubt, consider the mental welfare
  6506.               of the person who has to maintain the code after you,
  6507.               and who will probably put parens in the wrong place.
  6508.  
  6509.           2.  Don't go through silly contortions to exit a loop at the
  6510.               top or the bottom, when perl provides the "last"
  6511.               operator so you can exit in the middle.  Just outdent it
  6512.               a little to make it more visible:
  6513.  
  6514.                   line:
  6515.                    for (;;) {
  6516.                        statements;
  6517.                    last line if $foo;
  6518.                        next line if /^#/;
  6519.                        statements;
  6520.                    }
  6521.  
  6522.  
  6523.           3.  Don't be afraid to use loop labels--they're there to
  6524.               enhance readability as well as to allow multi-level loop
  6525.               breaks.  See last example.
  6526.  
  6527.  
  6528.  
  6529.  
  6530.  
  6531.      Page 99                                         (printed 1/17/94)
  6532.  
  6533.  
  6534.  
  6535.  
  6536.  
  6537.  
  6538.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6539.  
  6540.  
  6541.  
  6542.           4.  For portability, when using features that may not be
  6543.               implemented on every machine, test the construct in an
  6544.               eval to see if it fails.  If you know what version or
  6545.               patchlevel a particular feature was implemented, you can
  6546.               test $] to see if it will be there.
  6547.  
  6548.           5.  Choose mnemonic identifiers.
  6549.  
  6550.           6.  Be consistent.
  6551.  
  6552.           DDDDeeeebbbbuuuuggggggggiiiinnnngggg
  6553.  
  6554.           If you invoke perl with a ----dddd switch, your script will be run
  6555.           under a debugging monitor.  It will halt before the first
  6556.           executable statement and ask you for a command, such as:
  6557.  
  6558.           h           Prints out a help message.
  6559.  
  6560.           T           Stack trace.
  6561.  
  6562.           s           Single step.  Executes until it reaches the
  6563.                       beginning of another statement.
  6564.  
  6565.           n           Next.  Executes over subroutine calls, until it
  6566.                       reaches the beginning of the next statement.
  6567.  
  6568.           f           Finish.  Executes statements until it has
  6569.                       finished the current subroutine.
  6570.  
  6571.           c           Continue.  Executes until the next breakpoint is
  6572.                       reached.
  6573.  
  6574.           c line      Continue to the specified line.  Inserts a one-
  6575.                       time-only breakpoint at the specified line.
  6576.  
  6577.           <CR>        Repeat last n or s.
  6578.  
  6579.           l min+incr  List incr+1 lines starting at min.  If min is
  6580.                       omitted, starts where last listing left off.  If
  6581.                       incr is omitted, previous value of incr is used.
  6582.  
  6583.           l min-max   List lines in the indicated range.
  6584.  
  6585.           l line      List just the indicated line.
  6586.  
  6587.           l           List next window.
  6588.  
  6589.           -           List previous window.
  6590.  
  6591.           w line      List window around line.
  6592.  
  6593.  
  6594.  
  6595.  
  6596.  
  6597.      Page 100                                        (printed 1/17/94)
  6598.  
  6599.  
  6600.  
  6601.  
  6602.  
  6603.  
  6604.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6605.  
  6606.  
  6607.  
  6608.           l subname   List subroutine.  If it's a long subroutine it
  6609.                       just lists the beginning.  Use "l" to list more.
  6610.  
  6611.           /pattern/   Regular expression search forward for pattern;
  6612.                       the final / is optional.
  6613.  
  6614.           ?pattern?   Regular expression search backward for pattern;
  6615.                       the final ? is optional.
  6616.  
  6617.           L           List lines that have breakpoints or actions.
  6618.  
  6619.           S           Lists the names of all subroutines.
  6620.  
  6621.           t           Toggle trace mode on or off.
  6622.  
  6623.           b line condition
  6624.                       Set a breakpoint.  If line is omitted, sets a
  6625.                       breakpoint on the line that is about to be
  6626.                       executed.  If a condition is specified, it is
  6627.                       evaluated each time the statement is reached and
  6628.                       a breakpoint is taken only if the condition is
  6629.                       true.  Breakpoints may only be set on lines that
  6630.                       begin an executable statement.
  6631.  
  6632.           b subname condition
  6633.                       Set breakpoint at first executable line of
  6634.                       subroutine.
  6635.  
  6636.           d line      Delete breakpoint.  If line is omitted, deletes
  6637.                       the breakpoint on the line that is about to be
  6638.                       executed.
  6639.  
  6640.           D           Delete all breakpoints.
  6641.  
  6642.           a line command
  6643.                       Set an action for line.  A multi-line command
  6644.                       may be entered by backslashing the newlines.
  6645.  
  6646.           A           Delete all line actions.
  6647.  
  6648.           < command   Set an action to happen before every debugger
  6649.                       prompt.  A multi-line command may be entered by
  6650.                       backslashing the newlines.
  6651.  
  6652.           > command   Set an action to happen after the prompt when
  6653.                       you've just given a command to return to
  6654.                       executing the script.  A multi-line command may
  6655.                       be entered by backslashing the newlines.
  6656.  
  6657.           V package   List all variables in package.  Default is main
  6658.                       package.
  6659.  
  6660.  
  6661.  
  6662.  
  6663.      Page 101                                        (printed 1/17/94)
  6664.  
  6665.  
  6666.  
  6667.  
  6668.  
  6669.  
  6670.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6671.  
  6672.  
  6673.  
  6674.           ! number    Redo a debugging command.  If number is omitted,
  6675.                       redoes the previous command.
  6676.  
  6677.           ! -number   Redo the command that was that many commands
  6678.                       ago.
  6679.  
  6680.           H -number   Display last n commands.  Only commands longer
  6681.                       than one character are listed.  If number is
  6682.                       omitted, lists them all.
  6683.  
  6684.           q or ^D     Quit.
  6685.  
  6686.           command     Execute command as a perl statement.  A missing
  6687.                       semicolon will be supplied.
  6688.  
  6689.           p expr      Same as "print DB'OUT expr".  The DB'OUT
  6690.                       filehandle is opened to /dev/tty, regardless of
  6691.                       where STDOUT may be redirected to.
  6692.  
  6693.           If you want to modify the debugger, copy perldb.pl from the
  6694.           perl library to your current directory and modify it as
  6695.           necessary.  (You'll also have to put -I. on your command
  6696.           line.)  You can do some customization by setting up a
  6697.           .perldb file which contains initialization code.  For
  6698.           instance, you could make aliases like these:
  6699.  
  6700.               $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
  6701.               $DB'alias{'stop'} = 's/^stop (at|in)/b/';
  6702.               $DB'alias{'.'} =
  6703.                 's/^\./p "\$DB\'sub(\$DB\'line):\t",\$DB\'line[\$DB\'line]/';
  6704.  
  6705.  
  6706.           SSSSeeeettttuuuuiiiidddd SSSSccccrrrriiiippppttttssss
  6707.  
  6708.           Perl is designed to make it easy to write secure setuid and
  6709.           setgid scripts.  Unlike shells, which are based on multiple
  6710.           substitution passes on each line of the script, perl uses a
  6711.           more conventional evaluation scheme with fewer hidden
  6712.           "gotchas".  Additionally, since the language has more
  6713.           built-in functionality, it has to rely less upon external
  6714.           (and possibly untrustworthy) programs to accomplish its
  6715.           purposes.
  6716.  
  6717.           In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are
  6718.           intrinsically insecure, but this kernel feature can be
  6719.           disabled.  If it is, perl can emulate the setuid and setgid
  6720.           mechanism when it notices the otherwise useless setuid/gid
  6721.           bits on perl scripts.  If the kernel feature isn't disabled,
  6722.           perl will complain loudly that your setuid script is
  6723.           insecure.  You'll need to either disable the kernel setuid
  6724.           script feature, or put a C wrapper around the script.
  6725.  
  6726.  
  6727.  
  6728.  
  6729.      Page 102                                        (printed 1/17/94)
  6730.  
  6731.  
  6732.  
  6733.  
  6734.  
  6735.  
  6736.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6737.  
  6738.  
  6739.  
  6740.           When perl is executing a setuid script, it takes special
  6741.           precautions to prevent you from falling into any obvious
  6742.           traps.  (In some ways, a perl script is more secure than the
  6743.           corresponding C program.)  Any command line argument,
  6744.           environment variable, or input is marked as "tainted", and
  6745.           may not be used, directly or indirectly, in any command that
  6746.           invokes a subshell, or in any command that modifies files,
  6747.           directories or processes.  Any variable that is set within
  6748.           an expression that has previously referenced a tainted value
  6749.           also becomes tainted (even if it is logically impossible for
  6750.           the tainted value to influence the variable).  For example:
  6751.  
  6752.                $foo = shift;            # $foo is tainted
  6753.                $bar = $foo,'bar';       # $bar is also tainted
  6754.                $xxx = <>;               # Tainted
  6755.                $path = $ENV{'PATH'};    # Tainted, but see below
  6756.                $abc = 'abc';            # Not tainted
  6757.  
  6758.                system "echo $foo";      # Insecure
  6759.                system "/bin/echo", $foo;     # Secure (doesn't use sh)
  6760.                system "echo $bar";      # Insecure
  6761.                system "echo $abc";      # Insecure until PATH set
  6762.  
  6763.                $ENV{'PATH'} = '/bin:/usr/bin';
  6764.                $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  6765.  
  6766.                $path = $ENV{'PATH'};    # Not tainted
  6767.                system "echo $abc";      # Is secure now!
  6768.  
  6769.                open(FOO,"$foo");        # OK
  6770.                open(FOO,">$foo");       # Not OK
  6771.  
  6772.                open(FOO,"echo $foo|");  # Not OK, but...
  6773.                open(FOO,"-|") || exec 'echo', $foo;    # OK
  6774.  
  6775.                $zzz = `echo $foo`;      # Insecure, zzz tainted
  6776.  
  6777.                unlink $abc,$foo;        # Insecure
  6778.                umask $foo;              # Insecure
  6779.  
  6780.                exec "echo $foo";        # Insecure
  6781.                exec "echo", $foo;       # Secure (doesn't use sh)
  6782.                exec "sh", '-c', $foo;   # Considered secure, alas
  6783.  
  6784.           The taintedness is associated with each scalar value, so
  6785.           some elements of an array can be tainted, and others not.
  6786.  
  6787.           If you try to do something insecure, you will get a fatal
  6788.           error saying something like "Insecure dependency" or
  6789.           "Insecure PATH".  Note that you can still write an insecure
  6790.           system call or exec, but only by explicitly doing something
  6791.           like the last example above.  You can also bypass the
  6792.  
  6793.  
  6794.  
  6795.      Page 103                                        (printed 1/17/94)
  6796.  
  6797.  
  6798.  
  6799.  
  6800.  
  6801.  
  6802.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6803.  
  6804.  
  6805.  
  6806.           tainting mechanism by referencing subpatterns--perl presumes
  6807.           that if you reference a substring using $1, $2, etc, you
  6808.           knew what you were doing when you wrote the pattern:
  6809.  
  6810.                $ARGV[0] =~ /^-P(\w+)$/;
  6811.                $printer = $1;      # Not tainted
  6812.  
  6813.           This is fairly secure since \w+ doesn't match shell
  6814.           metacharacters.  Use of .+ would have been insecure, but
  6815.           perl doesn't check for that, so you must be careful with
  6816.           your patterns.  This is the ONLY mechanism for untainting
  6817.           user supplied filenames if you want to do file operations on
  6818.           them (unless you make $> equal to $<).
  6819.  
  6820.           It's also possible to get into trouble with other operations
  6821.           that don't care whether they use tainted values.  Make
  6822.           judicious use of the file tests in dealing with any user-
  6823.           supplied filenames.  When possible, do opens and such after
  6824.           setting $> = $<.  Perl doesn't prevent you from opening
  6825.           tainted filenames for reading, so be careful what you print
  6826.           out.  The tainting mechanism is intended to prevent stupid
  6827.           mistakes, not to remove the need for thought.
  6828.  
  6829.      EEEENNNNVVVVIIIIRRRROOOONNNNMMMMEEEENNNNTTTT
  6830.           HOME        Used if chdir has no argument.
  6831.  
  6832.           LOGDIR      Used if chdir has no argument and HOME is not
  6833.                       set.
  6834.  
  6835.           PATH        Used in executing subprocesses, and in finding
  6836.                       the script if -S is used.
  6837.  
  6838.           PERLLIB     A colon-separated list of directories in which
  6839.                       to look for Perl library files before looking in
  6840.                       the standard library and the current directory.
  6841.  
  6842.           PERLDB      The command used to get the debugger code.  If
  6843.                       unset, uses
  6844.  
  6845.                            require 'perldb.pl'
  6846.  
  6847.  
  6848.           Apart from these, perl uses no other environment variables,
  6849.           except to make them available to the script being executed,
  6850.           and to child processes.  However, scripts running setuid
  6851.           would do well to execute the following lines before doing
  6852.           anything else, just to keep people honest:
  6853.  
  6854.               $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  6855.               $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'} ne '';
  6856.               $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  6857.  
  6858.  
  6859.  
  6860.  
  6861.      Page 104                                        (printed 1/17/94)
  6862.  
  6863.  
  6864.  
  6865.  
  6866.  
  6867.  
  6868.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6869.  
  6870.  
  6871.  
  6872.      AAAAUUUUTTTTHHHHOOOORRRR
  6873.           Larry Wall <lwall@netlabs.com>
  6874.           MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
  6875.  
  6876.      FFFFIIIILLLLEEEESSSS
  6877.           /tmp/perl-eXXXXXX   temporary file for ----eeee commands.
  6878.  
  6879.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  6880.           a2p  awk to perl translator
  6881.           s2p  sed to perl translator
  6882.  
  6883.      DDDDIIIIAAAAGGGGNNNNOOOOSSSSTTTTIIIICCCCSSSS
  6884.           Compilation errors will tell you the line number of the
  6885.           error, with an indication of the next token or token type
  6886.           that was to be examined.  (In the case of a script passed to
  6887.           perl via ----eeee switches, each ----eeee is counted as one line.)
  6888.  
  6889.           Setuid scripts have additional constraints that can produce
  6890.           error messages such as "Insecure dependency".  See the
  6891.           section on setuid scripts.
  6892.  
  6893.      TTTTRRRRAAAAPPPPSSSS
  6894.           Accustomed awk users should take special note of the
  6895.           following:
  6896.  
  6897.           *   Semicolons are required after all simple statements in
  6898.               perl (except at the end of a block).  Newline is not a
  6899.               statement delimiter.
  6900.  
  6901.           *   Curly brackets are required on ifs and whiles.
  6902.  
  6903.           *   Variables begin with $ or @ in perl.
  6904.  
  6905.           *   Arrays index from 0 unless you set $[.  Likewise string
  6906.               positions in substr() and index().
  6907.  
  6908.           *   You have to decide whether your array has numeric or
  6909.               string indices.
  6910.  
  6911.           *   Associative array values do not spring into existence
  6912.               upon mere reference.
  6913.  
  6914.           *   You have to decide whether you want to use string or
  6915.               numeric comparisons.
  6916.  
  6917.           *   Reading an input line does not split it for you.  You
  6918.               get to split it yourself to an array.  And the split
  6919.               operator has different arguments.
  6920.  
  6921.           *   The current input line is normally in $_, not $0.  It
  6922.               generally does not have the newline stripped.  ($0 is
  6923.               the name of the program executed.)
  6924.  
  6925.  
  6926.  
  6927.      Page 105                                        (printed 1/17/94)
  6928.  
  6929.  
  6930.  
  6931.  
  6932.  
  6933.  
  6934.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  6935.  
  6936.  
  6937.  
  6938.           *   $<digit> does not refer to fields--it refers to
  6939.               substrings matched by the last match pattern.
  6940.  
  6941.           *   The print statement does not add field and record
  6942.               separators unless you set $, and $\.
  6943.  
  6944.           *   You must open your files before you print to them.
  6945.  
  6946.           *   The range operator is "..", not comma.  (The comma
  6947.               operator works as in C.)
  6948.  
  6949.           *   The match operator is "=~", not "~".  ("~" is the one's
  6950.               complement operator, as in C.)
  6951.  
  6952.           *   The exponentiation operator is "**", not "^".  ("^" is
  6953.               the XOR operator, as in C.)
  6954.  
  6955.           *   The concatenation operator is ".", not the null string.
  6956.               (Using the null string would render "/pat/ /pat/"
  6957.               unparsable, since the third slash would be interpreted
  6958.               as a division operator--the tokener is in fact slightly
  6959.               context sensitive for operators like /, ?, and <.  And
  6960.               in fact, . itself can be the beginning of a number.)
  6961.  
  6962.           *   Next, exit and continue work differently.
  6963.  
  6964.           *   The following variables work differently
  6965.  
  6966.                      Awk               Perl
  6967.                      ARGC              $#ARGV
  6968.                      ARGV[0]           $0
  6969.                      FILENAME          $ARGV
  6970.                      FNR               $. - something
  6971.                      FS                (whatever you like)
  6972.                      NF                $#Fld, or some such
  6973.                      NR                $.
  6974.                      OFMT              $#
  6975.                      OFS               $,
  6976.                      ORS               $\
  6977.                      RLENGTH           length($&)
  6978.                      RS                $/
  6979.                      RSTART            length($`)
  6980.                      SUBSEP            $;
  6981.  
  6982.  
  6983.           *   When in doubt, run the awk construct through a2p and see
  6984.               what it gives you.
  6985.  
  6986.           Cerebral C programmers should take note of the following:
  6987.  
  6988.           *   Curly brackets are required on ifs and whiles.
  6989.  
  6990.  
  6991.  
  6992.  
  6993.      Page 106                                        (printed 1/17/94)
  6994.  
  6995.  
  6996.  
  6997.  
  6998.  
  6999.  
  7000.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  7001.  
  7002.  
  7003.  
  7004.           *   You should use "elsif" rather than "else if"
  7005.  
  7006.           *   Break and continue become last and next, respectively.
  7007.  
  7008.           *   There's no switch statement.
  7009.  
  7010.           *   Variables begin with $ or @ in perl.
  7011.  
  7012.           *   Printf does not implement *.
  7013.  
  7014.           *   Comments begin with #, not /*.
  7015.  
  7016.           *   You can't take the address of anything.
  7017.  
  7018.           *   ARGV must be capitalized.
  7019.  
  7020.           *   The "system" calls link, unlink, rename, etc. return
  7021.               nonzero for success, not 0.
  7022.  
  7023.           *   Signal handlers deal with signal names, not numbers.
  7024.  
  7025.           Seasoned sed programmers should take note of the following:
  7026.  
  7027.           *   Backreferences in substitutions use $ rather than \.
  7028.  
  7029.           *   The pattern matching metacharacters (, ), and | do not
  7030.               have backslashes in front.
  7031.  
  7032.           *   The range operator is .. rather than comma.
  7033.  
  7034.           Sharp shell programmers should take note of the following:
  7035.  
  7036.           *   The backtick operator does variable interpretation
  7037.               without regard to the presence of single quotes in the
  7038.               command.
  7039.  
  7040.           *   The backtick operator does no translation of the return
  7041.               value, unlike csh.
  7042.  
  7043.           *   Shells (especially csh) do several levels of
  7044.               substitution on each command line.  Perl does
  7045.               substitution only in certain constructs such as double
  7046.               quotes, backticks, angle brackets and search patterns.
  7047.  
  7048.           *   Shells interpret scripts a little bit at a time.  Perl
  7049.               compiles the whole program before executing it.
  7050.  
  7051.           *   The arguments are available via @ARGV, not $1, $2, etc.
  7052.  
  7053.           *   The environment is not automatically made available as
  7054.               variables.
  7055.  
  7056.  
  7057.  
  7058.  
  7059.      Page 107                                        (printed 1/17/94)
  7060.  
  7061.  
  7062.  
  7063.  
  7064.  
  7065.  
  7066.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  7067.  
  7068.  
  7069.  
  7070.      EEEERRRRRRRRAAAATTTTAAAA AAAANNNNDDDD AAAADDDDDDDDEEEENNNNDDDDAAAA
  7071.           The Perl book, Programming Perl , has the following
  7072.           omissions and goofs.
  7073.  
  7074.           On page 5, the examples which read
  7075.  
  7076.                eval "/usr/bin/perl
  7077.  
  7078.           should read
  7079.  
  7080.                eval "exec /usr/bin/perl
  7081.  
  7082.  
  7083.           On page 195, the equivalent to the System V sum program only
  7084.           works for very small files.  To do larger files, use
  7085.  
  7086.                undef $/;
  7087.                $checksum = unpack("%32C*",<>) % 32767;
  7088.  
  7089.  
  7090.           The descriptions of alarm and sleep refer to signal
  7091.           SIGALARM.  These should refer to SIGALRM.
  7092.  
  7093.           The ----0000 switch to set the initial value of $/ was added to
  7094.           Perl after the book went to press.
  7095.  
  7096.           The ----llll switch now does automatic line ending processing.
  7097.  
  7098.           The qx// construct is now a synonym for backticks.
  7099.  
  7100.           $0 may now be assigned to set the argument displayed by ps
  7101.           (1).
  7102.  
  7103.           The new @###.## format was omitted accidentally from the
  7104.           description on formats.
  7105.  
  7106.           It wasn't known at press time that s///ee caused multiple
  7107.           evaluations of the replacement expression.  This is to be
  7108.           construed as a feature.
  7109.  
  7110.           (LIST) x $count now does array replication.
  7111.  
  7112.           There is now no limit on the number of parentheses in a
  7113.           regular expression.
  7114.  
  7115.           In double-quote context, more escapes are supported: \e, \a,
  7116.           \x1b, \c[, \l, \L, \u, \U, \E.  The latter five control
  7117.           up/lower case translation.
  7118.  
  7119.           The $$$$//// variable may now be set to a multi-character
  7120.           delimiter.
  7121.  
  7122.  
  7123.  
  7124.  
  7125.      Page 108                                        (printed 1/17/94)
  7126.  
  7127.  
  7128.  
  7129.  
  7130.  
  7131.  
  7132.      eeeevvvveeeellll 33336666))))     PPPPEEEERRRRLLLL((((1111))))
  7133.  
  7134.  
  7135.  
  7136.           There is now a g modifier on ordinary pattern matching that
  7137.           causes it to iterate through a string finding multiple
  7138.           matches.
  7139.  
  7140.           All of the $^X variables are new except for $^T.
  7141.  
  7142.           The default top-of-form format for FILEHANDLE is now
  7143.           FILEHANDLE_TOP rather than top.
  7144.  
  7145.           The eval {} and sort {} constructs were added in version
  7146.           4.018.
  7147.  
  7148.           The v and V (little-endian) template options for pack and
  7149.           unpack were added in 4.019.
  7150.  
  7151.      BBBBUUUUGGGGSSSS
  7152.           Perl is at the mercy of your machine's definitions of
  7153.           various operations such as type casting, atof() and
  7154.           sprintf().
  7155.  
  7156.           If your stdio requires an seek or eof between reads and
  7157.           writes on a particular stream, so does perl.  (This doesn't
  7158.           apply to sysread() and syswrite().)
  7159.  
  7160.           While none of the built-in data types have any arbitrary
  7161.           size limits (apart from memory size), there are still a few
  7162.           arbitrary limits: a given identifier may not be longer than
  7163.           255 characters, and no component of your PATH may be longer
  7164.           than 255 if you use -S.  A regular expression may not
  7165.           compile to more than 32767 bytes internally.
  7166.  
  7167.           Perl actually stands for Pathologically Eclectic Rubbish
  7168.           Lister, but don't tell anyone I said that.
  7169.  
  7170.  
  7171.  
  7172.  
  7173.  
  7174.  
  7175.  
  7176.  
  7177.  
  7178.  
  7179.  
  7180.  
  7181.  
  7182.  
  7183.  
  7184.  
  7185.  
  7186.  
  7187.  
  7188.  
  7189.  
  7190.  
  7191.      Page 109                                        (printed 1/17/94)
  7192.  
  7193.  
  7194.  
  7195.